191. Number of 1 Bits

97 阅读1分钟

题目描述

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

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.

解题思路1: 暴力求解

暴力求解, 将二进制数变成字符串, 遍历

示例代码1

def hammingWeight(n: int) -> int:
    n = format(n, "032b")
    count = 0
    for c in n:
        if c == "1":
            count += 1
    return count

解题思路2: 位运算

使用位运算, 每次拿到最后一位的1

示例代码2:

def hammingWeight(n: int) -> int:
    count = 0
    while n != 0:
        n = n & (n - 1)
        count += 1
    return count

解题思路3: 内置函数

使用python的内置函数 count(), 直接一行代码搞定

示例代码3:

def hammingWeight(n: int) -> int:
    return str(bin(n)).count("1")