We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent ea7d06a commit 3f882bdCopy full SHA for 3f882bd
Bit-Manipulation/LogTwo.js
@@ -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
@@ -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)))
+ })
0 commit comments