Question
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?
Solution
This can be generalized for any 【prime】 number n.
Lets say we have 2 number m & n.
If m is a power of n then for any number p,
1. For all p<=m
2. m%p = 0 if and only if p is also a power of n
We can use this concept here also. In this case n=3 and m is largest 32bit signed integer which is power of 3, i.e. 1162261467.
bool isPowerOfThree(int p) {
return p>0 && 1162261467%p == 0 ;
}
特别注意,上面解法只适用于素数。
另外有一些其他解法:
3的倍数在int范围内是有限的,所以可以打表,用hash_map来查找。
Another question
231.Power of Two
Given an integer, write a function to determine if it is a power of two.
Solution
解法1:
跟上面那题同理,2的power也满足该定理:
bool isPowerOfTwo(int n) {
return (n > 0) && (!(2147483648%n)); //2147483648 = 2^31
}
解法2:
从n的二进制角度看,如果n是2的power,那么n的二进制表示中有且仅有一个1位。
如果判断这个1位?
只需要判断 n&(n-1) 是否为0,如果是,则说明n中只有一个1位。
bool isPowerOfTwo(int n) {
return n>0 && !(n&(n-1));
}
这种解法更加高明,位运算很快,而且充分利用了二进制的性质。