Skip to content

Latest commit

 

History

History
72 lines (63 loc) · 1.44 KB

File metadata and controls

72 lines (63 loc) · 1.44 KB

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.

Solutions (Rust)

1. Compare Last Two Bits

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
    }
}

2. Calculate the Valid Numbers

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
    }
}