Leetcode 693. 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.
Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101
Input: n = 7
Output: false
Explanation: The binary representation of 7 is: 111
Input: n = 11
Output: false
Explanation: The binary representation of 11 is: 1011
Input: n = 10
Output: true
Explanation: The binary representation of 10 is: 1010
n
?
n
is a positive integer, which typically means any positive integer within the range of a 32-bit integer.XOR
of n
with n >> 1
. If n
has alternating bits, the result will be all 1’s. For example, for n = 5
(binary 101
), n >> 1
is 010
, and 101 XOR 010 = 111
.1
bit in its binary representation). This condition ensures that the result is indeed all 1’s.n ^ (n >> 1)
.(result & (result - 1)) == 0
.#include <iostream>
class Solution {
public:
bool hasAlternatingBits(int n) {
int xor_result = n ^ (n >> 1);
return (xor_result & (xor_result + 1)) == 0;
}
};
int main() {
Solution solution;
// Test cases
int test_case_1 = 5;
int test_case_2 = 7;
int test_case_3 = 11;
int test_case_4 = 10;
std::cout << "Test Case 1 (5): " << solution.hasAlternatingBits(test_case_1) << std::endl; // Expected Output: true
std::cout << "Test Case 2 (7): " << solution.hasAlternatingBits(test_case_2) << std::endl; // Expected Output: false
std::cout << "Test Case 3 (11): " << solution.hasAlternatingBits(test_case_3) << std::endl; // Expected Output: false
std::cout << "Test Case 4 (10): " << solution.hasAlternatingBits(test_case_4) << std::endl; // Expected Output: true
return 0;
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?