Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Java Solution 1 – Naive Iteration
public boolean isPowerOfFour(int num) { while(num>0){ if(num==1){ return true; } if(num%4!=0){ return false; }else{ num=num/4; } } return false; } |
Java Solution 2 – Bit Manipulation
public boolean isPowerOfFour(int num) { int count0=0; int count1=0; while(num>0){ if((num&1)==1){ count1++; }else{ count0++; } num>>=1; } return count1==1 && (count0%2==0); } |
Java Solution 3 – Math Equation
We can use the following formula to solve this problem without using recursion/iteration.
public boolean isPowerOfFour(int num) { if(num==0) return false; int pow = (int) (Math.log(num) / Math.log(4)); if(num==Math.pow(4, pow)){ return true; }else{ return false; } } |
public boolean isPowerOfFour(int n) {
if(n > 1;
}
return (count0 % 2 == 0);
}
why so complex :O ….checkout this one – with explanation
https://discuss.leetcode.com/topic/76414/one-line-java-no-complex-coding-using-only-integer-class-methods
return Integer.bitCount(num) == 1 && (Integer.toBinaryString(num).length()-1)%2==0;
Here’s a simple solution:
return num > 0 && (num & (num – 1)) == 0 && (num & 0x55555555) == num;
In the “num==Math.pow(4, pow)”, it can be replaced by just check whether pow is an integer.
public class Solution {
public boolean isPowerOfFour(int num) {
if(num == 0) return false;
double pow = Math.log(num)/Math.log(4);
if((int) pow == pow){
return true;
}
return false;
}
}