标签:
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 Four
判断一个数是否为3的次方数,且不能使用循环或递归,即要求时间和空间复杂度都为常数!
思路1
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 };
思路2
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 };
思路3
1 class Solution { 2 public: 3 bool isPowerOfThree(int n) { 4 return (n > 0 && 1162261467 % n == 0); 5 } 6 };
标签:
原文地址:http://www.cnblogs.com/whl2012/p/5665286.html