One Pager Cheat Sheet
- Write a method
powerOfThreewhich determines if a given non zero positive integernumbetween1and2147483647is apower of 3, with an expected space complexity ofO(logn)and an expected time complexity ofO(1). - The
^6in3^6stands 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-loopcan be considered as a repeatingIF-statementbecause 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 notationas3^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.
xxxxxxxxxx42
}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
Alright, well done! Try another walk-through.
If you had any problems with this tutorial, check out the main forum thread here.


