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.
  • Examples:
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.
  • Analysis:
Let the input number n is A31 A30 ..... A0.

Check the adjacent bits which are Ai and A(i-1).

Use "xor" bitwise to check these two adjacent bits.
  • Code - Java:
class Solution {
    public boolean hasAlternatingBits(int n) {
        int val = n & 1;
        n >>= 1;
        while (n > 0) {
            int last = n & 1;
            if ((val ^ last) == 0) {
                return false;
            }
            val = last;
            n >>= 1;
        }
        return true;
    }
}
  • Code - C++:
class Solution {
public:
    bool hasAlternatingBits(int n) {
        int val = n & 1;
        n >>= 1;
        while (n > 0) {
            int last = n & 1;
            if ((val ^ last) == 0) {
                return false;
            }
            val = last;
            n >>= 1;
        }
        return true;
    }
};
  • Code - Python:
class Solution(object):
    def hasAlternatingBits(self, n):
        """
        :type n: int
        :rtype: bool
        """
        val = n & 1
        n >>= 1
        while n > 0:
            last = n & 1
            if (val ^ last) == 0:
                return False
            val = last
            n >>= 1
        return True
  • Code - C:
bool hasAlternatingBits(int n) {
    int val = n & 1;
    n >>= 1;
    while (n > 0) {
        int last = n & 1;
        if ((val ^ last) == 0) {
            return false;
        }
        val = last;
        n >>= 1;
    }
    return true;
}

results matching ""

    No results matching ""