Accepted one line solution with explanation


  • 1
    L

    Here's the code

    public boolean isPowerOfTwo(int n) {
           return  (n > 0) && ((n & (n - 1)) == 0);
    }
    

    Looking on the binary representation of a number is is a power of 2, such number must have only one bit set.
    we can use a simple loop to count number of bits that are set.

    int cnt = 0;
    while(n > 0){
        cnt+=(n&1);
        n>>>=1;
    }
    return cnt == 1;
    

    Do we need to loop ? .. No.
    If a binary number n has 1 bit set then (n & (n - 1)) should equal 0. Why ? assume n = 8 (bit 3 is set) (1000) then n-1 = 7. Hence n-1 is the largest number you can represent using 3 bits, the largest number should have all bits set.


Log in to reply
 

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