Binary Number with Alternating Bits

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.

LeetCode Problem - 693

class Solution {
    // Method to check if the binary representation of a number has alternating bits
    public boolean hasAlternatingBits(int n) {
        // Convert the integer to a binary string representation
        String binaryString = Integer.toBinaryString(n);
        // Convert the binary string to a character array for easier manipulation
        char[] byteArr = binaryString.toCharArray();

        // Iterate through the character array
        for (int i = 0; i < byteArr.length - 1; i++) {
            // If two consecutive bits are the same, return false
            if (byteArr[i] == byteArr[i + 1]) {
                return false;
            }
        }

        // If no consecutive bits are the same, return true
        return true;
    }
}