We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1 Output: true Explanation: 20 = 1
Example 2:
Input: 16 Output: true Explanation: 24 = 16
Example 3:
Input: 218 Output: false
求一个数是否为2的幂次方。
2的整数次幂对应的二进制数只含有0个或者1个1,所以我们要做的就是判断输入的数的二进制表达形式里是否符合这一条件。有一种corner case需要注意,当输入的数为负数的时候,一定不是2的幂。
当然还有个小问题,就是表达式if (n & 1 == 1)一直报错“ bad operand types for binary operator '&'”,因为相对于位运算符,恒等运算符优先级大一点,这样就导致了“&”左边是int型,右边是boolean型(基础)。
class Solution { public: bool isPowerOfTwo(int n) { if (n <= 0) return false; bool hasOne = false; for (int i = 0; i < 32; ++i) { if (n & 1 == 1) { if (hasOne) { return false; } else { hasOne = true; } } n >>= 1; } return true; } };
参考资料: LeetCode原题
The text was updated successfully, but these errors were encountered:
No branches or pull requests
Given an integer, write a function to determine if it is a power of two.
Example 1:
Example 2:
Example 3:
求一个数是否为2的幂次方。
2的整数次幂对应的二进制数只含有0个或者1个1,所以我们要做的就是判断输入的数的二进制表达形式里是否符合这一条件。有一种corner case需要注意,当输入的数为负数的时候,一定不是2的幂。
当然还有个小问题,就是表达式if (n & 1 == 1)一直报错“ bad operand types for binary operator '&'”,因为相对于位运算符,恒等运算符优先级大一点,这样就导致了“&”左边是int型,右边是boolean型(基础)。
参考资料:
LeetCode原题
The text was updated successfully, but these errors were encountered: