Description
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
Solutions
This function checks whether a number has alternating bits in its binary representation. It first converts the number n to its binary string using toString(2), then iterates through each bit starting from the second position, comparing it with the previous bit. If any two consecutive bits are identical (both 0 or both 1), the function immediately returns false, meaning the bits are not alternating. If the loop completes without finding any matching consecutive bits, it returns true, confirming that all adjacent bits alternate between 0 and 1 (like the patterns 101010 or 010101).
/**
* @param {number} n
* @return {boolean}
*/
var hasAlternatingBits = function(n) {
const bin = n.toString(2);
for (let i = 1; i < bin.length; i++) {
if (bin[i] === bin[i - 1]) {
return false;
}
}
return true;
};