Number of 1 Bits (1有多少位)
上周刚刚开始学习Python,之前接触过C,R,Perl之类的变成语言,算是有一定基础。在数据分析领域,近些年R和Python在数据分析领域风声水起,作为立志做一名优秀数据分析师的菜鸟,怎能不把Python也熟悉熟悉。
我的Python入门流程:
- 在线Python教程 廖雪峰的官方网站
- Cousera在线课程 用Python玩转数据
学习程序怎么能光看书不练习写代码呢,正好拿一直想做的Leetcode练手啦^^
进入正题,今天的题目是:
Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011, so the function should return 3.
中文要求
写一个函数,接收参数为无符号整型数据,返回值为参数中1的个数(即汉明距离)。
例如,一个32位的整数11的二进制表示为00000000000000000000000000001011,所以函数返回值应为3。
该问题解决思路是,首先要将整数转化为二进制,然后再计算1的数量,讨论区大神有一行搞定的,如下:
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
return bin(n).count('1')
运行结果56ms
这里利用了Python自带的bin转换数字到二进制字符串,然后利用字符串自带的count方法统计1的数量。
这个代码改进一下可以更快, str(bin(n)).count('1'),运行结果52ms,但为什么会有这样的速度提升,我是不知道了。
由于数据在计算机中是按照二进制存储的,那么直接利用位运算是否能更快一些呢?
这里想,n = XXXXXX1000, n - 1 is XXXXXX0111. n & (n - 1) 是XXXXXX0000 正好去除了最后一位1
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
c = 0
while n:
n &= n - 1
c += 1
return c
运行结果还是56ms,基本没有提升。
截张图,56ms在大家提交的结果里还挺慢的,对比C和java更是慢了很多。说明python内建函数还是基于C优化过的,比自己的快多了,能用python自带的函数就尽量用吧。

讨论区里还有个有意思的想法,通过查找4位4位的比较(其实就是把1到15二进制包含1的数量列举出来,同理可扩展到更多):
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
bitsMap = [0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4]
i = 0
result = 0
while i < 32:
result += bitsMap[(n>>i) & 15]
i += 4
return result
可惜的是速度依然没有提升,结果52ms

浙公网安备 33010602011771号