2ms java using bit shift


  • 2
    S
    public class Solution {
    public boolean isPowerOfTwo(int n) {
        // power of 2 means only one bit has 1 and others are 0 
        return (countBitHasOne(n) == 1)? true : false; 
    }
    
    private int countBitHasOne(int n) {
        int count = 0; 
        while(n > 0) { 
            if((n & 1) == 1) {
                count++; 
            }
            
            // shift one bit
            n = n>>1;
        }
        return count; 
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.