mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 16:26:47 +08:00
algorithm: Log2 using bitwise operations (#1132)
This commit is contained in:
14
Bit-Manipulation/LogTwo.js
Normal file
14
Bit-Manipulation/LogTwo.js
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
/**
|
||||||
|
* https://handwiki.org/wiki/Binary_logarithm
|
||||||
|
* Approximate log2 using only bitwise operators
|
||||||
|
* @param {number} n
|
||||||
|
* @returns {number} Log2 approximation equal to floor(log2(n))
|
||||||
|
*/
|
||||||
|
export const logTwo = (n) => {
|
||||||
|
let result = 0
|
||||||
|
while (n >> 1) {
|
||||||
|
n >>= 1
|
||||||
|
result++
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
7
Bit-Manipulation/test/LogTwo.test.js
Normal file
7
Bit-Manipulation/test/LogTwo.test.js
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
import { logTwo } from '../LogTwo'
|
||||||
|
|
||||||
|
for (let i = 1; i < 100; i++) {
|
||||||
|
test('log2(' + i + ')', () => {
|
||||||
|
expect(logTwo(i)).toBe(Math.floor(Math.log2(i)))
|
||||||
|
})
|
||||||
|
}
|
Reference in New Issue
Block a user