Power of Two
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1 Output: true Explanation: 20 = 1
Example 2:
Input: 16 Output: true Explanation: 24 = 16
Example 3:
Input: 218 Output: false
METHOD 1:
class Solution {
public boolean isPowerOfTwo(int n) {
if(n<=0)
return false;
while(n>2){
int t = n>>1;
int c = t<<1;
if(n-c != 0)
return false;
n = n>>1;
}
return true;
}
}
If a number is power of 2, it's binary form should be 10...0. So if we
right shift a bit of the number and then left shift a bit, the value
should be the same when the number >= 10(i.e.,2).
Check below method for more optimized solution.
METHOD 2:
class Solution {
public boolean isPowerOfTwo(int n) {
return n>0 && (n&n-1)==0;
}
}
If a number is power of 2, then its highly bit is 1 and there is only one 1. Therefore, n & (n-1) is 0.
For example for 4 ( 100) and 16(10000), we get following after subtracting 1
3 –> 011
15 –> 01111
Related Posts:
Click here for May month challenges with solution and explanation
Click here for April month challenges with solution and explanation
Click here for May month challenges with solution and explanation
Click here for April month challenges with solution and explanation
Subscribe us to receive updates instantly.
Please let us know about your views in comment section.
Comments
Post a Comment