Skip to content

Commit 3f882bd

Browse files
author
alexander
committed
Add Bit-Manipulation/LogTwo
1 parent ea7d06a commit 3f882bd

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

Bit-Manipulation/LogTwo.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/*
2+
Approximate log2 using only bitwise operators
3+
*/
4+
5+
export const logTwo = (n) => {
6+
let result = 0
7+
while (n >> 1) {
8+
n >>= 1
9+
result++
10+
}
11+
return result
12+
}

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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy