From e44e35a35e5d0e7451752aeb460749c46cbabc91 Mon Sep 17 00:00:00 2001 From: Master Yi Date: Thu, 10 Mar 2022 11:53:01 +0800 Subject: [PATCH] refactor(math): refact to bitwise operators --- src/math.ts | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/src/math.ts b/src/math.ts index 63d1c53..732e1a7 100644 --- a/src/math.ts +++ b/src/math.ts @@ -140,13 +140,9 @@ export function cm(n: number, m: number) { * ``` */ export function bit(num: number, i: number) { - if (num < 0) num = num * -1 + if (num < 0) num = -num - while (i > 0) { - num = Math.floor(num / 2) - i-- - } - return num % 2 + return (num >> i) & 1 } /** @@ -163,11 +159,8 @@ export function bitCount(n: number) { let c = 0 while (n) { - if (n % 2 === 1) { - c++ - } - - n = Math.floor(n / 2) + c += 1 + n &= n - 1 } return c