Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Input: 5 Output: True Explanation: The binary representation of 5 is: 101
Input: 7 Output: False Explanation: The binary representation of 7 is: 111.
Input: 11 Output: False Explanation: The binary representation of 11 is: 1011.
Input: 10 Output: True Explanation: The binary representation of 10 is: 1010.
impl Solution {
pub fn has_alternating_bits(n: i32) -> bool {
let mut n = n;
let mut pre = n & 1;
while n != 0 {
n >>= 1;
if pre == n & 1 {
return false;
}
pre = n & 1;
}
true
}
}
impl Solution {
pub fn has_alternating_bits(n: i32) -> bool {
let mut i = 1;
while i > 0 && i < n {
match i % 2 {
1 => i = 2 * i,
_ => i = 2 * i + 1,
};
}
i == n
}
}