Here is the interview question prompt, presented for reference.
Given an integer num
, write a method to determine if it is a power of 3.
The method will be called as follows:
console.log(powerOfThree(9));
// true
console.log(powerOfThree(7));
// false
1
and 2147483647
O(logn)
O(1)
You can see the full challenge with visuals at this link.
Challenges • Asked about 5 years ago by Anonymous
This is the main discussion thread generated for Power Of Three.
function powerOfThree(num) {
if (num % 3 !== 0){
return false;
} else if (num === 3){
return true;
} else if (num % 3 === 0){
return powerOfThree(num / 3)
}
}
function powerOfThree2(num) {
var i = num;
while (i % 3 === 0 && i !== 3){
i = i / 3;
}
if (i % 3 !== 0){
return false;
} else if (i === 3){
return true;
}
}
console.log(powerOfThree(7));
console.log(powerOfThree(729));
def powerof3(num):
while num>3:
num = num/3
if num==3:
return True
else:
return False
function powerOfThree(num) {
return !!Math.pow(num, 1/3);
}
function powerOfThree(num) {
if (num % 3 === 0) return true;
else return false;
}
In the answer provided in the video if the number 1 is passed as an argument than it should be false not true. 1 is not a power of three.
Shouldnt the first return be false?
//code from Video
function powerOfThree(num) {
let currentQuotient = num;
if (currentQuotient === 1) {
return true;
}
while (currentQuotient>0) {
currentQuotient = currentQuotient /3;
if (currentQuotient === 1) {
return true;
}
}
return false;
}
console.log(powerOfThree(1));
Hey Rudy,
Don't forget that any number to the 0
th power or exponent is 1
(30 = 1). As such, we handle this edge case first.
Then we separately solve from the idea that after dividing, we'll eventually have a quotient of 1.
Yes you're right, got it thanks Jake!