Description#
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101
Example 2:
Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111.
Example 3:
Input: n = 11
Output: false
Explanation: The binary representation of 11 is: 1011.
Constraints:
Solutions#
Solution 1#
1
2
3
4
5
6
7
8
9
10
| class Solution:
def hasAlternatingBits(self, n: int) -> bool:
prev = -1
while n:
curr = n & 1
if prev == curr:
return False
prev = curr
n >>= 1
return True
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| class Solution {
public boolean hasAlternatingBits(int n) {
int prev = -1;
while (n != 0) {
int curr = n & 1;
if (prev == curr) {
return false;
}
prev = curr;
n >>= 1;
}
return true;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
| class Solution {
public:
bool hasAlternatingBits(int n) {
int prev = -1;
while (n) {
int curr = n & 1;
if (prev == curr) return false;
prev = curr;
n >>= 1;
}
return true;
}
};
|
1
2
3
4
5
6
7
8
9
10
11
12
| func hasAlternatingBits(n int) bool {
prev := -1
for n != 0 {
curr := n & 1
if prev == curr {
return false
}
prev = curr
n >>= 1
}
return true
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| impl Solution {
pub fn has_alternating_bits(mut n: i32) -> bool {
let u = n & 3;
if u != 1 && u != 2 {
return false;
}
while n != 0 {
if (n & 3) != u {
return false;
}
n >>= 2;
}
true
}
}
|
Solution 2#
1
2
3
4
| class Solution:
def hasAlternatingBits(self, n: int) -> bool:
n ^= n >> 1
return (n & (n + 1)) == 0
|
1
2
3
4
5
6
| class Solution {
public boolean hasAlternatingBits(int n) {
n ^= (n >> 1);
return (n & (n + 1)) == 0;
}
}
|
1
2
3
4
5
6
7
| class Solution {
public:
bool hasAlternatingBits(int n) {
n ^= (n >> 1);
return (n & ((long) n + 1)) == 0;
}
};
|
1
2
3
4
| func hasAlternatingBits(n int) bool {
n ^= (n >> 1)
return (n & (n + 1)) == 0
}
|
1
2
3
4
5
6
| impl Solution {
pub fn has_alternating_bits(n: i32) -> bool {
let t = n ^ (n >> 1);
(t & (t + 1)) == 0
}
}
|