zoukankan      html  css  js  c++  java
  • leetcode刷题笔记191 位1的个数

    题目描述:

    编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。

    示例:

    输入: 11
    输出: 3
    解释: 32位整数 11 的二进制表示为 00000000000000000000000000001011

    题目分析:

    判断32位二进制中1的个数,此题利用n&(n-1)性质可解

    解答代码:

    C++版:

    class Solution {
    public:
        int hammingWeight(uint32_t n) {
            int ans=0;
            while(n>0){
                n=n&(n-1);
                ans++;
            }
            return ans;
        }
    };
    Code

    Python版:

    class Solution(object):
        def hammingWeight(self, n):
            """
            :type n: int
            :rtype: int
            """
            ans=0
            while n>0:
                n=n&(n-1)
                ans+=1
            return ans
    Code

     

  • 相关阅读:
    linux 硬件信息
    docker note
    Shell cmd set note
    mysql management note
    scp noneed passwd
    update kernel
    数据包处理过程
    tcp/ip分片
    sockopt note
    Python note
  • 原文地址:https://www.cnblogs.com/qflyue/p/8973374.html
Copyright © 2011-2022 走看看