693. Binary Number with Alternating Bits LeetCode

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


 


Example 1:


Input: n = 5

Output: true

Explanation: The binary representation of 5 is: 101

Example 2:


Input: n = 7

Output: false

Explanation: The binary representation of 7 is: 111.

Example 3:


Input: n = 11

Output: false



Approach 1:

class Solution {
    public boolean hasAlternatingBits(int n) {
       
        String binary= Integer.toBinaryString(n);

        for(int i=1;i<binary.length();i++)
        {
            if(binary.charAt(i) == binary.charAt(i-1))
            {
                return false;
            }
        }
        return true;
    }
}

Approach 2:

class Solution {

    // Helper function to check if all bits in 'n' are 1s (e.g., 1, 3, 7, 15, etc.)
    public boolean bitOncheck(int n) {
        // Loop until n becomes 0
        while (n > 0) {
            // If the least significant bit is 0, it's not all 1s → return false
            if ((n & 1) == 0) {
                return false;
            }
            // Right shift n to check the next bit
            n = n >> 1;
        }
        // If all bits were 1s, return true
        return true;
    }

    // Main function to check if number has alternating bits (like 101010)
    public boolean hasAlternatingBits(int n) {
        // XOR n with n shifted right by 1
        // This gives a number with all bits set to 1 if bits in n were alternating
        int result = n ^ (n >> 1);

        // Check if result has all bits set to 1
        return bitOncheck(result);
    }
}


Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence