题目链接: https://leetcode-cn.com/problems/number-of-1-bits/ )
题目描述:
编写一个函数, 输入是一个无符号整数, 返回其二进制表达式中数字位数为 '1' 的个数 (也被称为汉明重量).
示例:
示例 1:
输入: 00000000000000000000000000001011
输出: 3
解释: 输入的二进制串 00000000000000000000000000001011 中, 共有三位为 '1'.
示例 2:
输入: 00000000000000000000000010000000
输出: 1
解释: 输入的二进制串 00000000000000000000000010000000 中, 共有一位为 '1'.
思路:
思路 1: 库函数
- class Solution(object):
- def hammingWeight(self, n):
- """
- :type n: int
- :rtype: int
- """ return bin(n).count("1")
思路 2: 位运算
- class Solution(object):
- def hammingWeight(self, n):
- """
- :type n: int
- :rtype: int
- """
- res = 0
- while n:
- res += (n & 1)
- n>>= 1
- return res
[LeetCode] 191. 位 1 的个数
来源: http://www.bubuko.com/infodetail-3159679.html