# 693. Binary Number with Alternating Bits

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

Example 1:

``````Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101
``````

Example 2:

``````Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.
``````

Example 3:

``````Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.
``````

Example 4:

``````Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.
``````

``````class Solution {
public:
bool hasAlternatingBits(int n) {
int bit = -1;
while (n > 0) {
if (n & 1 == 1) {
if (bit == 1) return false;
bit = 1;
} else {
if (bit == 0) return false;
bit = 0;
}
n >>= 1;
}
return true;
}
};
``````

``````class Solution {
public:
bool hasAlternatingBits(int n) {
int d = n & 1;
while ((n & 1) == d) {
d ^= 1;
n >>= 1;
}
return n == 0;
}
};
``````

``````class Solution {
public:
bool hasAlternatingBits(int n) {
return ((n + (n >> 1) + 1) & (n + (n >> 1))) == 0;
}
};
``````

``````class Solution {
public:
bool hasAlternatingBits(int n) {
return ((n ^= n / 4) & (n - 1)) == 0;
}
};
``````

Number of 1 Bits

https://discuss.leetcode.com/topic/106280/c-concise-code

https://discuss.leetcode.com/topic/106295/java-c-very-simple-solution-1-line

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation