题目:
编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。
Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).
示例 :
输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
提示:
- 请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
- 在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 3 中,输入表示有符号整数
-3
。
进阶:
如果多次调用这个函数,你将如何优化你的算法?
------------------------------------------------------------------------------
解法1:通过python的 bin()函数 和 count()函数 来实现。
bin() 返回一个整数 int 或者长整数 long int 的二进制表示。
count() 方法用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置。
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
# 注意bin()转换后的二进制结果为字符串
return bin(n).count('1')
601 / 601 个通过测试用例 | 状态: 通过 |
执行用时:44 ms |
解法2:通过 位运算 实现。
令 a = 0011 1100, b = 0000 1101
运算符 | 描述 | 实例 |
& | 按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0 | (a & b) 输出结果 12 ,二进制解释: 0000 1100 |
| | 按位或运算符:只要对应的二个二进位有一个为1时,结果位就为1。 | (a | b) 输出结果 61 ,二进制解释: 0011 1101 |
^ | 按位异或运算符:当两对应的二进位相异时,结果为1 | (a ^ b) 输出结果 49 ,二进制解释: 0011 0001 |
~ | 按位取反运算符:对数据的每个二进制位取反,即把1变为0,把0变为1 。~x 类似于 -x-1 | (~a ) 输出结果 -61 ,二进制解释: 1100 0011,在一个有符号二进制数的补码形式。 |
<< | 左移动运算符:运算数的各二进位全部左移若干位,由 << 右边的数字指定了移动的位数,高位丢弃,低位补0。 | a << 2 输出结果 240 ,二进制解释: 1111 0000 |
>> | 右移动运算符:把">>"左边的运算数的各二进位全部右移若干位,>> 右边的数字指定了移动的位数 | a >> 2 输出结果 15 ,二进制解释: 0000 1111 |
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0:
return 0
sum = 0
while n > 0:
# 先查看个位的值&1的结果
sum += n&1
# 相当于依次右移,然后计算下一位的值&1
n = n >> 1
return sum
601 / 601 个通过测试用例 | 状态: 通过 |
执行用时:28 ms |
解法3:通过python的 format()函数 和 map()函数 实现
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
sum = 0
# '{:b}'.format(n) 将整数n表示成二进制数字0和1组成的字符串列表,eg.['0','1','1','0']
# map(int, list()) 将字符串列表转换成数字列表,eg.[0,1,1,0]
l = list(map(int, list('{:b}'.format(n))))
for i in l:
sum += i
return sum
601 / 601 个通过测试用例 | 状态: 通过 |
执行用时:20 ms |
解法4:最常规也最容易想到的方法,逐次累加 n除2取余的结果(只有0和1两种结果)。
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
# 常规做法:
if n == 0:
return 0
sum = 0
while n > 0:
sum += n%2
n = n//2
return sum
601 / 601 个通过测试用例 | 状态: 通过 |
执行用时:28 ms |
参考:
https://www.runoob.com/python/python-func-bin.html