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 9843df6 commit d64e4fbCopy full SHA for d64e4fb
bit_manipulation/log_two.ts
@@ -0,0 +1,15 @@
1
+/**
2
+ * @author dev-madhurendra <https://github.com/dev-madhurendra>
3
+ * @see https://handwiki.org/wiki/Binary_logarithm
4
+ * Approximate log2 using bitwise operators
5
+ * @param {number} n
6
+ * @returns {number} Log2 approximation equal to floor(log2(n))
7
+ */
8
+export const logTwo = (n: number): number => {
9
+ let result = 0
10
+ while (n >> 1) {
11
+ n >>= 1
12
+ result++
13
+ }
14
+ return result
15
+}
bit_manipulation/test/log_two.test.ts
@@ -0,0 +1,10 @@
+import { logTwo } from "../log_two"
+
+describe('LogTwoTests' , () => {
+ test.each([...Array(100).keys()].map(i => [i + 1]))(
+ 'log2(%i)',
+ (input) => {
+ expect(logTwo(input)).toBe(Math.floor(Math.log2(input)));
+ );
+})
0 commit comments