Power of Three
一、题目
Given an integer, write a function to determine if it is a power of three.
Example 1:
Input: 27 Output: true
Example 2:
Input: 0 Output: false
Example 3:
Input: 9 Output: true
Example 4:
Input: 45 Output: false
Follow up:
Could you do it without using any loop / recursion?
二、解决方案
1.使用loop
1 /** 2 * @param {number} n 3 * @return {boolean} 4 */ 5 var isPowerOfThree = function(n) { 6 if(n<1){ 7 return false; 8 } 9 while(n%3===0){ 10 n = n/3; 11 } 12 return n===1; 13 };
除以3一直到1为止,注意代码能简略就简略,还要考虑边界值。
Notice that we need a guard to check that n != 0
, otherwise the while loop will never finish
时间复杂度: O(log_b(n))
空间复杂度:O(1)
2.