Skip to content

Commit 78f023f

Browse files
authored
algorithm: Log2 using bitwise operations (#1132)
1 parent 56713e8 commit 78f023f

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

Bit-Manipulation/LogTwo.js

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/**
2+
* https://handwiki.org/wiki/Binary_logarithm
3+
* Approximate log2 using only bitwise operators
4+
* @param {number} n
5+
* @returns {number} Log2 approximation equal to floor(log2(n))
6+
*/
7+
export const logTwo = (n) => {
8+
let result = 0
9+
while (n >> 1) {
10+
n >>= 1
11+
result++
12+
}
13+
return result
14+
}

Bit-Manipulation/test/LogTwo.test.js

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { logTwo } from '../LogTwo'
2+
3+
for (let i = 1; i < 100; i++) {
4+
test('log2(' + i + ')', () => {
5+
expect(logTwo(i)).toBe(Math.floor(Math.log2(i)))
6+
})
7+
}

0 commit comments

Comments
 (0)