Binary Number with Alternating Bits

easy bit manipulation

Problem

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

Inputn = 5
Outputtrue
Binary of 5 is "101" — adjacent bits differ.

def has_alternating_bits(n):
    x = n ^ (n >> 1)
    return (x & (x + 1)) == 0
function hasAlternatingBits(n) {
  const x = n ^ (n >> 1);
  return (x & (x + 1)) === 0;
}
class Solution {
    public boolean hasAlternatingBits(int n) {
        int x = n ^ (n >> 1);
        return (x & (x + 1)) == 0;
    }
}
bool hasAlternatingBits(int n) {
    long x = n ^ (n >> 1);
    return (x & (x + 1)) == 0;
}
Time: O(1) Space: O(1)