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?
Credits:
Special thanks to @yukuairoy for adding this problem and creating all test cases.
题目链接:https://leetcode.com/problems/power-of-four/
题目分析:O(1)判断是不是4的幂,一行代码不能更多了吧,首先必须是个整数,其次二进制中必须只有一个1且1的位置必须是(0x55555555)当中的某个
public class Solution {
public boolean isPowerOfFour(int num) {
return num > 0 && (num & (num - 1)) == 0 && ((num - 1) % 3) == 0;
}
}