LeetCode 191 Number of 1 Bits (Python)

Posted by 小明MaxMing on February 1, 2021

题目

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

解题思路

每次&1判断是否最后一位为1,之后右移一位

代码

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

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅