231.2的幂(javascript)231.PowerofTwo
原创给你一个整数 n,请判断整数是否为 2 权力如果是,返回 true ; 否则,返回 false 。
如果存在整数 x 使得 n == 2x ,则认为 n 是 2 权力
Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2x.
示例 1:
输入:n = 1
输出:true
解释:20 = 1示例 2:
输入:n = 16
输出:true
解释:24 = 16示例 3:
输入:n = 3
输出:false示例 4:
输入:n = 4
输出:true示例 5:
输入:n = 5
输出:false
var isPowerOfTwo = function (n) {
    while (n > 1) {
        if (n % 2 == 0) {
            n /= 2
        } else {
            break
        }
    }
    return n == 1
};解决问题的思路: https://leetcode-cn.com/problems/power-of-two/solution/power-of-two-er-jin-zhi-ji-jian-by-jyd/
- 若n=2^x 且x是一个自然数(即。n为2功率),则必须满足以下条件:
 1.恒有n&(n-1)==0,这是因为:
 n最高二进制位为1,所有剩余位为0;
 n-1最高二进制位为0,所有剩余位为1;
 2.一定满足n>0
- 因此 n>0且n&(n-1)==0可以确定是否满意。n=2^x
2^x
n
n-1
n & (n - 1)
2^0
0001
0000
(0001) & (0000) == 0
2^1
0010
0001
(0010) & (0001) == 0
2^2
0100
0011
(0100) & (0011) == 0
2^3
1000
0111
(1000) & (0111) == 0
…
…
…
…
var isPowerOfTwo = function (n) {
    return n > 0 && (n & (n - 1)) == 0
};leetcode: https://leetcode-cn.com/problems/power-of-two/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
 itfan123
itfan123







