How to use String Conversion In Javascript
In this approach, we convert the given number to its binary representation using string conversion. Then, we find the index of the first ‘1’ character in the binary string, representing the position of the first set bit. This method offers simplicity but might be less efficient compared to bitwise operations.
Example: Implementation to use logarithm and bitwise right shift to find the first set bit.
function findFirstSetBitString(number) {
const binaryString = number.toString(2);
const firstSetBitIndex =
binaryString.length - binaryString.indexOf('1');
return firstSetBitIndex;
}
console.log(findFirstSetBitString(10));
Output
4
Time Complexity: O(log n)
Auxiliary Space: O(log n)
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