One line java solution using bitCount


  • 84
    Q

    This is kind of cheating, but the idea is that a power of two in binary form has and only has one "1".

    public class Solution {
        public boolean isPowerOfTwo(int n) {
            return n>0 && Integer.bitCount(n) == 1;
        }
    }

  • 0
    Y
    This post is deleted!

  • 1
    D
    public boolean isPowerOfTwo(int n) {
        
         if(n<=0)
          return false;
               int log_base_2= (int)(Math.log(n)/Math.log(2));
           return (((n & (1<< log_base_2)) ==n)?true:false);
        
        
    }
    

    I used shift operator !


  • 2
    Y

    Same idea here. Count the number of ones (should be 1) by right shifting n by 32 times (be sure to kick out 0x80000000).

    public boolean isPowerOfTwo(int n) {
        if (n == 0x80000000) return false;
        int ones = 0;
        for (int i = 1; i <= 32; ++i) {         
            ones += n & 1;
            n = n >> 1;
        }
        return ones == 1;
    }
    

  • 0
    A

    @qxx I have the same, but this is actually not efficient =(


  • 0
    C
    public static boolean isPowerOfTwo(int n) {
            return n > 0 && Integer.highestOneBit(n) == Integer.lowestOneBit(n) ? true : false;
    }
    

    This is my solution. so easy to understand.


  • 0

    What is the runtime complexity of Integer.bitCount()? Is it O(n) where n is the number of bits of the integer?


Log in to reply
 

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