1332. Number of 1 Bits

偷懒暴力count

class Solution:
    """
    @param n: an unsigned integer
    @return: the number of ’1' bits
    """
    def hammingWeight(self, n):
        # write your code here
        return str(bin(n)).count('1')

follow-up: 如果是个类似 10110000000000 这样的数字,最后一个1之后的digits其实就不需要遍历,可以改善平均时间复杂度。

class Solution:
    """
    @param n: an unsigned integer
    @return: the number of ’1' bits
    """
    def hammingWeight(self, n):
        # write your code here
        bi = bin(n)[2:]
        res = 0;
        idx = 0
        while (int(bi) != 0) and idx <= len(bi)-1:
            if bi[idx] == '1':
                res += 1;
                # 把当前的1计算进去之后,就把它改成0,这样等所有1都算完,bi=0
                bi[idx] == 0
            idx += 1
        return res

Last updated

Was this helpful?