How to use logarithm and bitwise right shift In Javascript
In this approach, we are using bitwise AND (&) with the two’s complement of the number to isolate the rightmost set bit. Then, we use the logarithm (base 2) to find its position, accounting for 1-based indexing, to determine the position of the first set bit.
Example: Implementation to use logarithm and bitwise right shift to find the first set bit.
let num = 12;
if (num === 0) {
console.log("No set bit found");
} else {
console.log("Position of first set bit:",
Math.floor(Math.log2(num & -num)) + 1);
}
Output
Position of first set bit: 3
Time Complexity: O(1)
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
Contact Us