Power of two solution by Java


  • 0
    1
    class Solution {
        public boolean isPowerOfTwo(int n) {
              if(n<=0)   return false;
              
              while(n>0)
              {
                  if(n%2==0)   n/=2;
                  else if(n==1)  return true;  
                  else    return false;
              }
            return true;
        }
    }
    

  • 0
    S

    var isPowerOfTwo = function(n) {
    if (typeof n !== 'number')
    return 'Not a number';

    return n && (n & (n - 1)) === 0;
    

    }

    console.log(isPowerOfTwo(16));
    console.log(isPowerOfTwo(18));
    console.log(isPowerOfTwo(256));


Log in to reply
 

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