Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 78f023f

Browse files
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

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 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

Lines changed: 7 additions & 0 deletions
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)

AltStyle によって変換されたページ (->オリジナル) /