From 571ce5788e816d59fe6266e95a5eeeba36e965df Mon Sep 17 00:00:00 2001 From: jerryfishcode <91447694+jerryfishcode@users.noreply.github.com> Date: Mon, 27 Sep 2021 17:44:58 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A01356.=20=E5=A6=82=E4=BD=95?= =?UTF-8?q?=E8=AE=A1=E7=AE=97=E4=BA=8C=E8=BF=9B=E5=88=B6=E4=B8=AD1?= =?UTF-8?q?=E7=9A=84=E6=95=B0=E9=87=8F=20JavaScript=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1356.根据数字二进制下1的数目排序.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/problems/1356.根据数字二进制下1的数目排序.md b/problems/1356.根据数字二进制下1的数目排序.md index 06c29500..c7e856d1 100644 --- a/problems/1356.根据数字二进制下1的数目排序.md +++ b/problems/1356.根据数字二进制下1的数目排序.md @@ -166,6 +166,18 @@ class Solution { ## JavaScript ```js +var sortByBits = function(arr) { + const bitCount = n =>{// 计算n的二进制中1的数量 + let count = 0; + while(n){ + n &= (n - 1);// 清除最低位的1 + count++; + } + return count; + } + // 如果有差,则按bits数排,如果无差,则按原值排 + return arr.sort((a,b) => bitCount(a) - bitCount(b) || a - b); +}; ``` -----------------------