Leetcode 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:
Example 2:
Example 3:
Example 4:
To determine if a number has alternating bits, we can follow these steps:
A more efficient way involves avoiding the binary representation string manipulation:
public class Solution {
public boolean hasAlternatingBits(int n) {
// First, shift n right by one bit and XOR it with the original number
int shifted = n >> 1;
int xor = n ^ shifted;
// Check if xor + 1 is a power of 2, which means xor must be of the form '111...111'
return (xor & (xor + 1)) == 0;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.hasAlternatingBits(5)); // true
System.out.println(sol.hasAlternatingBits(7)); // false
System.out.println(sol.hasAlternatingBits(11)); // false
System.out.println(sol.hasAlternatingBits(10)); // true
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?