TreeviewCopyright © aleen42 all right reserved, powered by aleen42

191. 位1的个数

https://leetcode-cn.com/problems/number-of-1-bits/

Java

/*
 * @Author: Goog Tech
 * @Date: 2020-08-16 10:07:51
 * @LastEditTime: 2020-08-16 10:08:33
 * @Description: https://leetcode-cn.com/problems/number-of-1-bits/
 * @FilePath: \leetcode-googtech\#191. Number of 1 Bits\Solution.java
 * @WebSite: https://algorithm.show/
 */

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

'''
Author: Goog Tech
Date: 2020-08-16 10:07:58
LastEditTime: 2020-08-16 10:08:49
Description: https://leetcode-cn.com/problems/number-of-1-bits/
FilePath: \leetcode-googtech\#191. Number of 1 Bits\Solution.py
WebSite: https://algorithm.show/
'''

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 ""