Leetcode Note: Go - Sort Integers by the Number of 1 Bits

Sort Integers by The Number of 1 Bits - LeetCode
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/

  • Go 言語で取り組んだメモ

回答

Go solution using Standard Library functions. - Sort Integers by The Number of 1 Bits - LeetCode
https://leetcode.com/problems/sort-integers-by-the-number-of-1-bits/solutions/830935/go-solution-using-standard-library-functions/

func sortByBits(arr []int) []int {
	sort.Slice(arr, func(i, j int) bool {
		x, y := bits.OnesCount(uint(arr[i])), bits.OnesCount(uint(arr[j]))
		if x == y {
			return arr[i] < arr[j]
		}
		return x < y
	})
	return arr
}