Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Similar questions: Power of Three, Power of Two
Follow up:
Could you do it without using any loop / recursion?
Basic iterative solution:
class Solution {
public boolean isPowerOfFour(int num) {
if(num<=0) return false;
while(num!=1){
if(num%4!=0) return false;
num/=4;
}
return true;
}
}
Bitwise and math property solution:
Power of 2:
The binary representation of a power-of-two 2^x is a 1 followed only by 0s.
In such a case, x − 1 generates a binary number where the 1s turn into 0s and the former 0s turn into 1s.
For example, 8 = 1000b and 8 − 1 = 7 = 0111b.
So, x & x − 1 should be 0 if x is a power of two.
public boolean isPowerOfTwo(int n) {
return ((n & (n-1))==0 && n>0);
}
Power of 3:
maxPowerOfThree = 1162261467 = 3^19: (3^20>2^31)
public boolean isPowerOfThree(int n) {
return n > 0 && (1162261467 % n == 0);
}
Power of 4:
The basic idea is from power of 2:
Use n&(n-1) == 0 to determine if n is power of 2.
For power of 4, the additional restriction is that in binary form, the only “1” should always located at the odd position.
For example, 4^0 = 1, 4^1 = 100, 4^2 = 10000.
So we can use “num & 0x55555555==num” to check if “1” is located at the odd position.
public class Solution {
public boolean isPowerOfFour(int num) {
return (num > 0) && ((num & (num - 1)) == 0) && ((num & 0x55555555) == num);
}
}