Solution 1. Brute force
Divide number by 2 recursively and find it out.
Time complexity : O(log2n)
Solution 2. Use bitwise '&' of the number n and n-1
and check if it is equals to 0
n & (n-1) == 0
Example :
Number = 8
Binary of 8 = 1 0 0 0
Binary of 7 = 0 1 1 1
Bitwise '&' of both numbers : 0 0 0 0 = 0
Time complexity : O(1)
Example
private static boolean checkPowerOf2(int num) {
if((num & (num-1)) == 0) {
System.out.println(num+" is the power of 2");
} else {
System.out.println(num+" is not the power of 2");
}
}
No comments:
Post a Comment
Note: only a member of this blog may post a comment.