231. Power of Two

Description

Given an integer, write a function to determine if it is a power of two.

Solution

Solution 1

/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfTwo = function(n) {
    "use strict";
    if (n === 0) {
        return false;
    }
    while (n !== 1) {
        n /= 2;
        if (!Number.isInteger(n)) {
            return false;
        }
    }
    return true;
};

Solution 2

/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfTwo = function(n) {
    "use strict";
    if (n <= 0) {
        return false;
    }
    return (n&(n-1)) === 0;
};

results matching ""

    No results matching ""