693. Binary Number with Alternating Bits LeetCode Solution

In this guide, you will get 693. Binary Number with Alternating Bits LeetCode Solution with the best time and space complexity. The solution to Binary Number with Alternating Bits problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Binary Number with Alternating Bits solution in C++
  4. Binary Number with Alternating Bits solution in Java
  5. Binary Number with Alternating Bits solution in Python
  6. Additional Resources
693. Binary Number with Alternating Bits LeetCode Solution image

Problem Statement of 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:

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
Explanation: The binary representation of 11 is: 1011.

Constraints:

1 <= n <= 231 – 1

Complexity Analysis

  • Time Complexity: O(1)
  • Space Complexity: O(1)

693. Binary Number with Alternating Bits LeetCode Solution in C++

class Solution {
 public:
  bool hasAlternatingBits(int n) {
    //            n = 0b010101
    //       n >> 2 = 0b000101
    // n ^ (n >> 2) = 0b010000 = a
    //        a - 1 = 0b001111
    //  a & (a - 1) = 0
    const int a = n ^ (n >> 2);
    return (a & (a - 1)) == 0;
  }
};
/* code provided by PROGIEZ */

693. Binary Number with Alternating Bits LeetCode Solution in Java

class Solution {
  public boolean hasAlternatingBits(int n) {
    //            n = 0b010101
    //       n >> 2 = 0b000101
    // n ^ (n >> 2) = 0b010000 = a
    //        a - 1 = 0b001111
    //  a & (a - 1) = 0
    final int a = n ^ (n >> 2);
    return (a & (a - 1)) == 0;
  }
}
// code provided by PROGIEZ

693. Binary Number with Alternating Bits LeetCode Solution in Python

class Solution:
  def hasAlternatingBits(self, n: int) -> bool:
    #            n = 0b010101
    #       n >> 2 = 0b000101
    # n ^ (n >> 2) = 0b010000 = a
    #        a - 1 = 0b001111
    #  a & (a - 1) = 0
    a = n ^ (n >> 2)
    return (a & (a - 1)) == 0
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.