增加1356. 如何计算二进制中1的数量 JavaScript解法

This commit is contained in:
jerryfishcode
2021-09-27 17:44:58 +08:00
committed by GitHub
parent 195b8aefdd
commit 571ce5788e

View File

@ -166,6 +166,18 @@ class Solution {
## JavaScript ## JavaScript
```js ```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);
};
``` ```
----------------------- -----------------------