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?
这到题和Power of two类似,如果不能用递归循环做,就使用位操作。1个数是2的幂肯定是4的幂,但反过来不成立,4的幂只能是奇数位为1,而2的幂只有有一个位置为1就行。
所以先判断是否为2的幂,然后通过与.0X55555555(....1010101)进行&操作,保留奇数位,判断是否改变。
public boolean isPowerOfFour(int num) {
if(num<=0)
return false;
return (num & num-1)==0 && (num&0x55555555)==num;
}
本文介绍了一种不使用循环或递归的方法来检查一个32位有符号整数是否为4的幂。该方法利用了位操作,首先判断数字是否为2的幂,再进一步确认是否仅在奇数位上有1。

443

被折叠的 条评论
为什么被折叠?



