From 3f882bdb54e7e9719a20b426fedd7408f0a76c96 Mon Sep 17 00:00:00 2001 From: alexander Date: Thu, 6 Oct 2022 03:47:53 -0400 Subject: [PATCH 1/2] Add Bit-Manipulation/LogTwo --- Bit-Manipulation/LogTwo.js | 12 ++++++++++++ Bit-Manipulation/test/LogTwo.test.js | 7 +++++++ 2 files changed, 19 insertions(+) create mode 100644 Bit-Manipulation/LogTwo.js create mode 100644 Bit-Manipulation/test/LogTwo.test.js diff --git a/Bit-Manipulation/LogTwo.js b/Bit-Manipulation/LogTwo.js new file mode 100644 index 0000000000..86b705dad1 --- /dev/null +++ b/Bit-Manipulation/LogTwo.js @@ -0,0 +1,12 @@ +/* + Approximate log2 using only bitwise operators +*/ + +export const logTwo = (n) => { + let result = 0 + while (n>> 1) { + n>>= 1 + result++ + } + return result +} diff --git a/Bit-Manipulation/test/LogTwo.test.js b/Bit-Manipulation/test/LogTwo.test.js new file mode 100644 index 0000000000..e811f29b23 --- /dev/null +++ b/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))) + }) +} From e41ed9e22821dc59bd34d028c7bcc13469b14680 Mon Sep 17 00:00:00 2001 From: alexander Date: Thu, 6 Oct 2022 03:51:28 -0400 Subject: [PATCH 2/2] url --- Bit-Manipulation/LogTwo.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Bit-Manipulation/LogTwo.js b/Bit-Manipulation/LogTwo.js index 86b705dad1..844a7ac5e5 100644 --- a/Bit-Manipulation/LogTwo.js +++ b/Bit-Manipulation/LogTwo.js @@ -1,7 +1,9 @@ -/* - Approximate log2 using only bitwise operators -*/ - +/** + * https://handwiki.org/wiki/Binary_logarithm + * Approximate log2 using only bitwise operators + * @param {number} n + * @returns {number} Log2 approximation equal to floor(log2(n)) + */ export const logTwo = (n) => { let result = 0 while (n>> 1) {

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