Leetcode 1458 Solution

This article provides solution to leetcode question 1458 (sort-integers-by-the-number-of-1-bits)

https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits

Solution

class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        def get_ones(x):
            ans = 0
            while x:
                ans += 1
                x = x & (x - 1)
            return ans

        return sorted(arr, key=lambda ele: (get_ones(ele), ele))