Problem
We are required to write a JavaScript function that takes in an integer, num, as the first and the only argument.
Our function should check whether the binary representation of num has alternating bits − namely, if two adjacent bits will always have different values.
For example, if the input to the function is
Input
const num = 5;
Output
const output = true;
Output Explanation
Because the binary form of 5 is 101 which have alternating bits.
Example
Following is the code −
const num = 5; const isAlternating = (num = 1) => { const binary = num.toString(2); let curr = binary[0]; for(let i = 1; i < binary.length; i++){ const el = binary[i]; if(curr !== el){ curr = el; continue; }; return false; }; return true; }; console.log(isAlternating(num));
Output
true