Given an integer, write a function to determine if it is a power of three.
判断一个数是否为3的幂:
一,除数法,最容易想到的方法:
1. 首先是能够整除
2. 整除到最后的数一定为1则说明TRUE否则FALSE
bool isPowerOfThree(int n) {
if (n <= 0)
return false;
while(0 == (n % 3)){
n/=3;
}
return (n == 1);
}
二,根据整型数的特点,总结规律
boolean isPowerOfThree(int n) {
return (n > 0) && (1162261467 % n == 0);
}
引用从解答中的分析:
- MaxInt = 2232−1 since we use 32 bits to represent the number, half of the range is used for negative numbers and 0 is part of the positive numbers
Knowing the limitation of n
, we can now deduce that the maximum value of n
that is also a power of three is 1162261467. We calculate this as:
3⌊log3MaxInt⌋=3⌊19.56⌋=319=1162261467
Therefore, the possible values of n
where we should return true
are 30, 31 ... 319. Since 3 is a prime number, the only divisors of 319 are 30, 31 ... 319, therefore all we need to do is divide 319 by n
. A remainder of 0 means n
is a divisor of 319 and therefore a power of three.