Solution using Binary String


  • 0
    C

    class Solution {
    public boolean isPowerOfTwo(int n) {

        String binaryRep = null;
        binaryRep = Integer.toBinaryString(n);
        boolean result = false;
        int bitCount = 0;
        
        if (n > 0){
            
            for (char c : binaryRep.toCharArray()){
                if (c == '1'){
                    bitCount++;
                }
            }
            
            if(bitCount == 1){
                result = true;
            }
            
        }
    
        
        return result;
    }
    

    }

    If the input is negative, that number will never be the power of two. So the result must be false.
    And for non-negative numbers, we first convert the number into a binary string, and if there is more than one '1' in that string, the result should be false.
    For other cases, the result should be true.


Log in to reply
 

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