We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 56713e8 commit 78f023fCopy full SHA for 78f023f
Bit-Manipulation/LogTwo.js
@@ -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
@@ -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