The "Binary Number with Alternating Bits interview question" asks you to verify a specific property of an integer's binary representation. A number has alternating bits if no two adjacent bits are the same. For example, 5 (101) and 10 (1010) have alternating bits, while 7 (111) and 11 (1011) do not.
Yahoo and Amazon use the "Binary Number with Alternating Bits coding problem" to see if a candidate can find clever shortcuts using bitwise arithmetic. While you can solve this by checking bits one by one, there is a very elegant solution using XOR and bitwise properties that demonstrates a deeper understanding of "Bit Manipulation interview pattern."
There are two main ways to solve this:
n % 2 to get the last bit and compare it with the previous bit using n / 2.n by 1 (n >> 1) and XOR it with the original n (n ^ (n >> 1)), the result will be a string of all 1s if the bits were alternating.(x & (x + 1)) == 0. (Binary: 101)
010 (2).111 (7).Whenever you see a pattern in binary bits (like "all 1s" or "power of 2"), look for a bitwise formula. These are common "Bit Manipulation interview pattern" tricks that can save time and impress your interviewer.