leetcode 191. Number of 1 Bits(python)

236 阅读2分钟

描述

Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

Note:

Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3.

Example 1:

Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.	

Example 2:

Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.

Example 3:

Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

Note:

The input must be a binary string of length 32.

解析

根据题意,就是找出二进制的数字里面包含了多少个 1 ,可以直接将输入的数表示成二进制的字符串,统计 1 出现的个数,但是太粗暴,这里换一个思路。就是在循环里每次判断 n 不为 0 的时候, 计算 n&1 可以知道右边的数字是 1 还是 0 ,将结果加到 res 中,然后将 n 向右移动一位,继续进行上述操作,最后得到的 res 就是答案。

解答

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        res = 0
        while n:
            res += n & 1
            n >>= 1
        return res
        	      
		

运行结果

Runtime: 16 ms, faster than 83.66% of Python online submissions for Number of 1 Bits.
Memory Usage: 13.4 MB, less than 32.97% of Python online submissions for Number of 1 Bits.

原题链接:leetcode.com/problems/nu…

您的支持是我最大的动力