Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
Tags: Math
Similar Problems: (E) Power of Two (E) Power of Fourc++
判斷一個數是否爲3的次方數,且不能使用循環或遞歸,即要求時間和空間複雜度都爲常數!oop
思路1
spa
1 class Solution { 2 public: 3 bool isPowerOfThree(int n) { 4 while (n && n % 3 == 0) { 5 n /= 3; 6 } 7 return n == 1; 8 } 9 };
思路2code
1 class Solution { 2 public: 3 bool isPowerOfThree(int n) { 4 if(n==0) 5 return false; 6 if ((math.log10(n) / (math.log10(3))) - (int) ((math.log10(n) / (math.log10(3)))) ==0) 7 { 8 return true; 9 } 10 return false; 11 } 12 };
思路3blog
1 class Solution { 2 public: 3 bool isPowerOfThree(int n) { 4 return (n > 0 && 1162261467 % n == 0); 5 } 6 };