Solving Leetcode Interviews in Seconds with AI: Binary Number with Alternating Bits
Introduction
In this blog post, we will explore how to solve the LeetCode problem "693" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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
Explanation
Here's a breakdown of the approach, followed by the Python code:
- Bitwise Manipulation: Use bitwise operations to efficiently examine adjacent bits. Specifically, right shift the number and XOR it with the original number.
Check for Power of 3: If the number has alternating bits, the result of XORing it with its right-shifted version will be a number of the form (2k - 1), which is one less than a power of 2, which can be checked using the property
(n & (n + 1)) == 0.Runtime Complexity: O(1) & Storage Complexity: O(1)
Code
def hasAlternatingBits(n: int) -> bool:
"""
Checks if a positive integer has alternating bits in its binary representation.
"""
num = n ^ (n >> 1)
return (num & (num + 1)) == 0