Clean java Solution - 2 methods


  • 0
    Z
        // Method 1: decimal view
        public boolean isPowerOfTwo(int n) {
            if (n <= 0) {
                return false;
            }
            while (n % 2 == 0) {
                n /= 2;
            }
            
            return n == 1;
        }
        
        // Method 2: bit operation view
        public boolean isPowerOfTwo(int n) {
            if (n <= 0) {
                return false;
            }
            return (n & (n - 1)) == 0;
        }
    
    

Log in to reply
 

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