Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

231. Power of Two #202

Open Tcdian opened 4 years ago

Tcdian commented 4 years ago

231. Power of Two

给定一个整数,编写一个函数来判断它是否是 2 的幂次方。

Example 1

Input: 1
Output: true 
Explanation: 20 = 1

Example 2

Input: 16
Output: true
Explanation: 24 = 16

Example 3

Input: 218
Output: false
Tcdian commented 4 years ago

Solution

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