Total Accepted: 38815
Total Submissions: 118702
Difficulty: Easy
Given an integer, write a function to determine if it is a power of two.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
Hide Similar Problems
思路:
1.n中的二进制表示中只有一个1的符合;
2.令x = (n & n-1),由x是n去掉最后一个1的数,求法参考博文【23个位运算技巧】。
class Solution {
public:
bool isPowerOfTwo(int n) {
return n>0 && !(n & (n-1)); // n&(n-1)去掉最后一个1
}
};