只想到了可以原地计算
class Solution {
public:
bool hasAlternatingBits(int n) {
int tmp = n % 2;
n /= 2;
while(n){
if(n % 2 == tmp)
return false;
tmp = n % 2;
n /= 2;
}
return true;
}
};
没想到位运算(和进制相关,特别是二进制时常用)
题解:
class Solution {
public:
bool hasAlternatingBits(int n) {
long a = n ^ (n >> 1);
return (a & (a + 1)) == 0;
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/binary-number-with-alternating-bits/solution/jiao-ti-wei-er-jin-zhi-shu-by-leetcode-s-bmxd/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。