How to use bitwise AND and shifting In Javascript
In this approach, we are using the bitwise AND (&) operator with 1 to check each bit of the number from right to left. If a set bit is found, we determine its position by incrementing a counter variable (res) and breaking the loop.
Example: Implementation to use bitwise AND and shifting to find the first set bit.
let num = 18;
let res = 0;
while (num > 0) {
res++;
if (num & 1) {
console.log("Position of first set bit:", res);
break;
}
num >>= 1;
}
if (num === 0) {
console.log("No set bit found");
}
Output
Position of first set bit: 2
Time Complexity: O(log n)
Auxiliary Space: O(1)
JavaScript Program to Find First Set Bit
The rightmost bit in a binary representation of a number that is set to 1 is called the “First Set Bit”. It indicates the lowest significant bit where the value changes from 0 to 1.
Examples:
Input:
N = 18
Output:
2
Explanation:
Binary representation of 18 is 010010,the first set bit from the right side is at position 2.
Input:
N = 12
Output:
3
Explanation:
Binary representation of 12 is 1100, the first set bit from the right side is at position 3.
Table of Content
- Using bitwise AND and shifting
- Using logarithm and bitwise right shift
- Using String Conversion