Skip to content

Commit dab98d0

Browse files
author
alexander
committed
url
1 parent 3f882bd commit dab98d0

4 files changed

Lines changed: 21 additions & 19 deletions

File tree

Bit-Manipulation/BitwiseLogTwo.js

Lines changed: 14 additions & 0 deletions
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 bitwiseLogTwo = (n) => {
8+
let result = 0
9+
while (n >> 1) {
10+
n >>= 1
11+
result++
12+
}
13+
return result
14+
}

Bit-Manipulation/LogTwo.js

Lines changed: 0 additions & 12 deletions
This file was deleted.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import { bitwiseLogTwo } from '../BitwiseLogTwo'
2+
3+
for (let i = 1; i < 100; i++) {
4+
test('log2(' + i + ')', () => {
5+
expect(bitwiseLogTwo(i)).toBe(Math.floor(Math.log2(i)))
6+
})
7+
}

Bit-Manipulation/test/LogTwo.test.js

Lines changed: 0 additions & 7 deletions
This file was deleted.

0 commit comments

Comments
 (0)