标签:
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?
如果一个数为
0000000000000001
0000000000000100
0000000000010000
0000000001000000
0000000100000000
二进制表示中仅有一个1,且1位于奇数位处。
可将此题与 Power of Two进行类比,主要区别在于判断等于1的位是否位于奇数位处。
// Runtime: 2 ms
public class Solution {
public boolean isPowerOfFour(int num) {
return num > 0 && (num & (num - 1)) == 0 && (num & 0x55555555) != 0 ;
}
}
标签:
原文地址:http://blog.csdn.net/foreverling/article/details/51422916