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]))