zoukankan      html  css  js  c++  java
  • [LeetCode] 191. Number of 1 Bits 二进制数1的个数

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

    For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

    写一个函数操作无符号整数,返回整数的二进制数1的个数。

    解法:位操作Bit Manipulation

    使用n&(n-1)的方法

    假使 n =0x110101

                n       n-1     n&(n-1)

    step1: 110101 110100 110100

    step2: 110100 110011 110000

    step3: 110000 101111 100000

    step4: 100000 011111 000000

    发现有几个1,就循环几次n&(n-1)得到0。

    时间复杂度:O(M),M是n中1的个数

    Java:

    public class Solution {  
        public int NumberOf1(int n) {  
            int count = 0;  
            while (n != 0) {  
                n &= (n - 1);  
                count ++;  
            }  
            return count;  
        }  
    }  

    Python:

    class Solution:
        # @param n, an integer
        # @return an integer
        def hammingWeight(self, n):
            result = 0
            while n:
                n &= n - 1
                result += 1
            return result
    

    Python:

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

    Python:

    class Solution(object):
        def hammingWeight(self, n):
            """
            :type n: int
            :rtype: int
            """
            b = bin(n)
            return b.count('1')

    C++:

    class Solution {
    public:
        int hammingWeight(uint32_t n) {
            int res = 0;
            for (int i = 0; i < 32; ++i) {
                res += (n & 1);
                n = n >> 1;
            }
            return res;
        }
    }; 

    C++:

    class Solution {
    public:
        int hammingWeight(uint32_t n) {
            int count = 0;
            for (; n; n &= n - 1) {
                ++count;
            }
            return count;
        }
    };
    

     

    类似题目:

    [LeetCode] 190. Reverse Bits 翻转二进制位

     

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    mysql索引需要了解的几个注意
    apache配置--虚拟目录
    简化LINUX的命令输入 简化linux命令 快捷键 短路径
    apache vhost 访问权限配置
    php中常用设置
    win7配置nginx + php
    restful php
    php 笔记 汇总 学习
    mysql修改表结构
    mysql 优化工具
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8680698.html
Copyright © 2011-2022 走看看