Binary Number with Alternating Bits LeetCode Solution - The Coding Shala

Home >> LeetCode >> Binary Number with Alternating Bits

 In this post, we will learn how to solve LeetCode's Binary Number with Alternating Bits Problem and will implement its solution in Java.

Binary Number with Alternating Bits Problem

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.

LeetCode - Binary Number with Alternating Bits Java Solution

Approach 1

Compare alternate bits.

Java Program: 

class Solution {
    public boolean hasAlternatingBits(int n) {
        int i = 31;
        //find first 1 bit from left side
        while(((n >> i) & 1) == 0) i--;
        
        int prevBit = (n>>i) & 1;
        i--;
        while(i >= 0) {
            int currBit = (n >> i) & 1;
            if(currBit == prevBit) return false;
            prevBit = currBit;
            i--;
        }
        return true;
    }
}

Approach 2

Divide by two.

Java Program: 

class Solution {
    public boolean hasAlternatingBits(int n) {
        int prevBit = n%2;
        n /= 2;
        while(n > 0) {
            int currBit = n%2;
            if(currBit == prevBit) return false;
            prevBit = currBit;
            n /= 2;
        }
        return true;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala