LeetCode 693: Binary Number with Alternating Bits Solution
Master LeetCode problem 693 (Binary Number with Alternating Bits), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
693. Binary Number with Alternating Bits
Problem Explanation
Explanation
To solve this problem, we can iterate through the bits of the given integer and check if any two adjacent bits are the same. If we find any two adjacent bits that are the same, we return false, indicating that the integer does not have alternating bits. If we reach the end of the iteration without finding any two adjacent bits that are the same, we return true, indicating that the integer has alternating bits.
- Time complexity: O(log n) where n is the given integer
- Space complexity: O(1)
Solution Code
class Solution {
public boolean hasAlternatingBits(int n) {
int prevBit = n & 1;
n >>= 1;
while (n > 0) {
int currBit = n & 1;
if (currBit == prevBit) {
return false;
}
prevBit = currBit;
n >>= 1;
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 693 (Binary Number with Alternating Bits)?
This page provides optimized solutions for LeetCode problem 693 (Binary Number with Alternating Bits) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 693 (Binary Number with Alternating Bits)?
The time complexity for LeetCode 693 (Binary Number with Alternating Bits) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 693 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 693 in Java, C++, or Python.