Binary Number with Alternating Bits LeetCode Solution - The Coding Shala
Home >> LeetCode >> Binary Number with Alternating Bits
Other Posts You May Like
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; } }
- LeetCode - Letter Case Permutation
- LeetCode - Decode XORed Array
- LeetCode - Number of 1 bit
- LeetCode - Detect Capital
- LeetCode - Flipping an Image
Comments
Post a Comment