JavaScript 1 line(trick) solution and 2 lines(normal) solution


  • 0
    Z
    /**
     * @param {number} n
     * @return {boolean}
     */
    var isPowerOfTwo = function(n) {
        return n<=0 ? false : !(n&(n-1));
    };
    
    /**
     * @param {number} n
     * @return {boolean}
     */
    var isPowerOfTwo = function(n) {
        while(!(n&1) && n > 0) n = n>>>1;
        return n === 1 ? true : false;
    };
    

  • 0
    Z

    Here is another 1 line cheating solution.

    return n < 1 ? false : 2147483648 % n === 0;
    

Log in to reply
 

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