leetcode: 1356. Sort Integers by The Number of 1 Bits
1. 計算數字中bit1的個數
在這裏,計算1 bit 的個數使用的是 減1再 bit and的方式。
例如 9的二進制表示爲 1001:
(1)減1 後爲 1000, 1001&1000 = 1000.
(2)1000 減1 後爲 0111, 1000&0111 = 0000.
因此9的bit 1 個數爲2.
實際上每次減1再and,就消去了原數字二進制表示中一個1。
2. python的多層排序
因爲題目中除了要求按照 bit1 個數排序外,還要求在“1的個數”相同的情況下,按照數值大小排序。因此就需要2層排序。python中使用sort的key參數,可以自定義排序規則,結合lambda表達式可以實現多層排序。
代碼如下
class Solution:
def numberof1s(self, number):
count = 0
n = number
while n:
count = count + 1
n = (n-1) & n
return count
def sortByBits(self, arr):
# lambda 表達式表示 有2層排序:首先按照1的個數排序,然後按照數值大小排序
arr.sort(key=lambda x: (self.numberof1s(x), x))
return arr
s = Solution()
print(s.sortByBits([1024,513,256,128,64,32,16,8,4,2,1]))