One Pager Cheat Sheet
- Write a method
powerOfThree
which determines if a given non zero positive integernum
between1
and2147483647
is apower of 3
, with an expected space complexity ofO(logn)
and an expected time complexity ofO(1)
. - The
^6
in3^6
stands for the exponent calculated using the formulabase^exponent = result
. - Loops are a useful control structure in programming used to repeat certain code
multiple times
, saving the developer time when dealing with large data sets or unknown iterations. - The
while-loop
can be considered as a repeatingIF-statement
because it needs an initial evaluation of the condition before continuing to repeat a certain set of instructions as long as the condition is true. - The number 729 can be expressed using
exponential notation
as3^6
, since it is the result of raising 3 to the 6th power. - The exponential value of any number can be calculated
without loops
, simply by raising that number to the power of itself. - We can solve this problem in
O(logn)
time complexity andO(1)
space complexity by continuously dividing the number by3
.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
42
}
var assert = require('assert');
​
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(9));
console.log(powerOfThree(7));
​
try {
assert.equal(powerOfThree(9), true);
​
console.log('PASSED: ' + 'powerOfThree(9) should be true');
} catch (err) {
console.log(err);
}
​
try {
assert.equal(powerOfThree(7), false);
​
console.log('PASSED: ' + 'powerOfThree(7) should be false');
} catch (err) {
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Got more time? Let's keep going.
If you had any problems with this tutorial, check out the main forum thread here.