Skip to content

LeetCode题解:231. 2的幂,位运算取二进制中最右边的1,JavaScript,详细注释 #215

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
chencl1986 opened this issue Nov 7, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:https://leetcode-cn.com/problems/power-of-two/

解题思路:

  1. 只有大于0的数才可以是2的幂
  2. 2的幂在二进制中满足条件:一个1后跟n个0,例如8=00001000
  3. 如果不是2的幂,其二进制中有不止一个1,例如6=00000110
  4. 因此只需要判断二进制是否满足条件一个1后跟n个0即可,判断方法如下:
    • n=8为例,8的二进制为00001000,-8的二进制为111110008 & -8 = 00001000等于8。
    • n=6为例,6的二进制为00000110,-6的二进制为111110106 & -6 = 00000010不等于6。
    • n=7为例,7的二进制为00000111,-7的二进制为111110017 & -7 = 00000001不等于7。
    • 因此要判断n是否2的幂,只需判断(n & -n) === n即可。如需查看更详细的分析,请看官方题解
/**
 * @param {number} n
 * @return {boolean}
 */
var isPowerOfTwo = function (n) {
  // 判断n大于0,且满足(n & -n) === n。
  return n > 0 && (n & -n) === n;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant