Posts

Showing posts with the label Power of Two

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: 2 0  = 1 Example 2: Input: 16 Output: true Explanation: 2 4  = 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; } } Try it on Leetcode 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; } } Try it on Leetcode If a number is power of 2, then i