TreeviewCopyright © aleen42 all right reserved, powered by aleen42

15. 二进制中 1 的个数

https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/

Java

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        // 使用与(&)运算,即两位同时为1时结果才为1
        return n == 0 ? 0 : 1 + hammingWeight(n & (n - 1));
    }
}

Python

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = 0
        # bin() 函数返回一个 int 或者长整型 long int 的二进制表示
        for i in str(bin(n)):
            if i == '1': count += 1
        return count
Copyright © GoogTech 2021 all right reserved,powered by GitbookLast update time : 2021-09-15 01:55:05

results matching ""

    No results matching ""