leetcode_693
Solutions
class Solution {
public:
bool hasAlternatingBits(int n) {
while (n) {
if ((n & 0b1) > 0 == (n & 0b10) > 0)
return false;
n >>= 1;
}
return true;
}
};class Solution {
public:
bool hasAlternatingBits(int n) {
// 10101010 ^ 01010101 = 11111111
n = n ^ (n >> 1);
// 11111111 + 1 = 1000000000 & 11111111 = 00000000
// if n == INT_MAX, INT_MAX + 1 will cause runtime error
return n == INT_MAX || !(n & (n + 1));
}
};Last updated