Int determines whether a power of 3 - Leetcode (326)

leetcode链接:326. Power of Three

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?

General universal solution:

      
      
1
2
3
4
5
6
7
8
9
10
11
      
      
class Solution {
public:
bool isPowerOfThree(int n) {
while (n >= 3 ){
if(n % 3 != 0)
return false;
n /= 3;
}
return n>0 && n != 2;
}
};

By the above, but the topic that best try acyclic or recursive solution.

I feel such a method is a little tricky. For example, to find the intlargest factor in the range of 3, so that any multiple of 3 nmay be divisible thereof.

      
      
1
2
3
4
5
6
7
8
9
10
11
      
      
class Solution {
public:
bool isPowerOfThree(int n) {
// Method 2
const int maxint = 0x7fffffff;
//假设3^k 是int范围内最大的3的幂
int k = int(log(maxint) / log(3));
int max_power_3 = pow(3,k);
return n>0 && max_power_3 % n ==0;
}
};

或者将上述代码压缩到一行:

      
      
1
      
      
return n> 0 && int( pow( 3, int( log( 0x7fffffff) / log( 3)))) % n == 0;

pow函数在头文件math.h中。

同类题:

  1. 231. Power of Two
  2. 326. Power of Three
  3. 342. Power of Four

原文:大专栏  判断int是否为3的幂—— Leetcode(326)


Guess you like

Origin www.cnblogs.com/chinatrump/p/11589237.html