How to use & and shift operator In Javascript
Initialize m as 1 and check its & with the bits, starting from the rightmost bit. Left shift m by one till we find the first set bit. The first set bit will give a number when we perform & operation with m.
Example: The example below shows how to return the position of the rightmost set bit in JavaScript using & and shift operator.
function rightBit(n) {
let position = 1;
let m = 1;
while ((n & m) == 0) {
// left shift
m = m << 1;
position++;
}
return position;
}
let n = 20;
// function call
console.log(rightBit(n));
Output
3
Time Complexity: O(log2n)
Auxiliary Space: O(1)
JavaScript Program to Find the Position of the Rightmost Set Bit
Given a number, the task is to find the position of the rightmost set bit. The indexing is from right to left, where the rightmost bit position starts from 1.
Example:
Input: n = 20
Output: 3
Explanation: Binary Representation of 20 is 10100, hence position of first set bit from right is 3.
Input: n = 48
Output: 5
Explanation: Binary Representation of 48 is 110000, hence position of first set bit from right is 5.
Below are the approaches to finding the position of the rightmost set bit using JavaScript:
Table of Content
- Using (n & ~ (n – 1))
- Using & and shift operator
Contact Us