How to use Logarithms In Javascript
In this approach, we are using logarithms (Math.log2) to find the position of the leftmost set bit in the given integer, and then using Math.pow to calculate the value of that bit, resulting in res containing only the leftmost set bit value.
Syntax:
Math.log2(x)
Example: The below example uses Logarithms to extract the leftmost set bit of a given integer in JavaScript.
let num = 40;
let res = Math.pow(2,
Math.floor(Math.log2(num)));
console.log(res);
Output
32
JavaScript Program to Extract the Leftmost Set Bit of a Given Integer
We are given an integer value the task is to extract the leftmost set bit of a given integer in JavaScript. The leftmost set bit is a bit whose value is 1 and is present at the leftmost position in binary representation.
The below approaches can be implemented to extract the leftmost set bit.
Table of Content
- Using Bitwise Operations
- Using Logarithms
- Using Binary String Conversion