题目描述:
Given an integer, write a function to determine if it is a power of two.
也就是判断一个数是否是2的幂
我的代码如下:
class Solution {
public:
bool isPowerOfTwo(int n) {
if (n & (n - 1) == 0) {
return true;
}
else {
return false;
}
}
};
我的这段代码无法通过测试点:2
在JS中, === 的优先级是10 , & 的优先级是9. 因此会先计算 === 然后计算 &,因此你的答案应该增加括号(括号的优先级最高,为20),使得先进行 & 运算,再进行 === 运算。
参考: https://developer.mozilla.org...