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?
代码:
class Solution {
public:
bool isPowerOfThree(int n) {
return n>0?!(1162261467 % n):0; //162261467 = 3^19
}
};
3的幂的数也就下面这些:
1||3||9||27||81||243||729||2187|| 6561|| 19683 || 59049 || 177147 || 531441 || 1594323 || 4782969 || 14348907 || 43046721 || 129140163 || 387420489 || 162261467
那么怎么证明162261467不能被 3^n - 3^(n+1) 之间的数整除呢?
例如n=5:
3^19 / ( 3^5+0) --- 3^19 / ( 3^5+1)---3^19 / ( 3^5+3^5) ----3^19 / ( 3^5+2*3^5-1) ----3^19 / ( 3^5+2*3^5)
分别为:3^14/(1+0)--- 3^14 / ( 1+1/3^5)---3^14 / ( 1+1) ----3^14/ ( 1+2-1/3^5) ----3^14 / (3^5+2)
这些分母都在(1,3)之间(开区间)。所以不可能再整除3^14了。
所以说区间(3^5, 3^6)之间的数都不能整除3^19了。
342. Power of Four:
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
4^15是最大值。与上面题目一样,eg: 4^15/(4^4)与 4^15/(4^5)之间还有个2*4^5能被4^15整除,反映在二进制数形式上面,就是只含有1个1的数都能被4^15整除,而真正满足条件的是,只有偶数位为1的数才是4的power。这时就要想办法排除这种情况。
可以用 (num&0x55555555)==num来排除2*(2^n)的情况,也就是排除奇数位为1的那些数。
代码:
class Solution {
public:
bool isPowerOfFour(int num) {
if(num<=0) return false;
int max = pow(4,15);
return (max%num==0&&(num&0x55555555)==num)?true:false;
}
};