How to use bitwise manipulation In Javascript
In this approach we perform a bitwise AND operation between the number and its right-shifted version by one bit. If the result is zero, it means there are no common set bits between adjacent bits, indicating an alternate bit pattern. Otherwise, it returns false.
Example: To demonstrate checking if a number has bits in an alternate pattern.
function hasAltBitPattern(n) {
if (n > 1) {
return (n & (n >> 1)) === 0;
} else {
return false;
}
}
let numToCheck = 100;
if (hasAltBitPattern(numToCheck)) {
console.log("Yes");
} else {
console.log("No");
}
Output
Yes
Time Complexity: O(1)
Auxiliary Space: O(1)
JavaScript Program to Check if a Number has Bits in an Alternate Pattern
JavaScript can be used to assess whether a given number follows an alternating pattern in its binary representation. By examining the binary digits of the number, one can determine if the sequence alternates between 0s and 1s, aiding in understanding the binary structure of the input.
Examples:
Input : 15
Output : No
Explanation: Binary representation of 15 is 1111.
Input : 10
Output : Yes
Explanation: Binary representation of 10 is 1010.
Below are the methods to check if a number has bits in an alternate pattern:
Table of Content
- Using binary conversion
- Using bitwise manipulation