[leetcode] 1356. Sorting according to the number of 1s in digital binary (implemented by js)

1. Topic

1356. Sort by Number of 1s in Binary
insert image description here

2. Idea

  1. Define a get1Cnt function to calculate the number of 1s in the binary representation of the number num;
  • The method of counting the number of 1s in the binary number is: continuously take out the last bit of the binary number num, if it is 1, add 1 to the counter a, and then shift num to the right by one bit, that is, each bit of the binary number is Traverse it until num is 0.
  1. Sorting, if the number of 1 in the binary representation of the number is different, sort according to the number of 1 from small to large; if the number is the same, then sort according to the size of the number itself from large to small.

3. Code implementation

/**
 * @param {number[]} arr
 * @return {number[]}
 */
var sortByBits = function(arr) {
    
    
    function get1Cnt(num) {
    
    
        let cnt = 0
        while (num) {
    
    
            // 取个位,如果是1则加到cnt
            cnt += num & 1
            // num右移一位
            num >>= 1
        }
        return cnt
    }
    return arr.sort((a, b) => {
    
    
        return get1Cnt(a) !== get1Cnt(b) ? get1Cnt(a) - get1Cnt(b) : a - b
    })
};

4. Reference

The code is concise and a good solution

Guess you like

Origin blog.csdn.net/weixin_44109827/article/details/129398787