693. Binary Number with Alternating Bits
/**
* Problem: LeetCode 693 - Binary Number with Alternating Bits
* Difficulty: Easy
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public boolean hasAlternatingBits(int n) {
long x = n ^ (n >> 1);
return (x & (x + 1)) == 0;
}
}
"""
Problem: LeetCode 693 - Binary Number with Alternating Bits
Difficulty: Easy
Language: Python
Author: CodeByTushu
"""
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
x = n ^ (n >> 1)
return (x & (x + 1)) == 0
/**
* Problem: LeetCode 693 - Binary Number with Alternating Bits
* Difficulty: Easy
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
bool hasAlternatingBits(int n) {
long long x = n ^ (n >> 1);
return (x & (x + 1)) == 0;
}
};
/**
* Problem: LeetCode 693 - Binary Number with Alternating Bits
* Difficulty: Easy
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {number} n
* @return {boolean}
*/
var hasAlternatingBits = function(n) {
const x = n ^ (n >> 1);
return ((x + 1) & x) === 0;
};