leetcode 191. Number of 1 Bits 详解 python3

一.问题描述

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

Example 1:

Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.

Example 2:

Input: 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.

Example 3:

Input: 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.

Note:

  • Note that in some languages such as Java, there is no unsigned integer type. In this case, the input will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
  • In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3 above the input represents the signed integer -3.

Follow up:

If this function is called many times, how would you optimize it?

二.解题思路

1.粗暴的方法

bin(num)直接查看num的二进制,然后迭代每个字符,判断是不是1,是的话就计数器+1.当然会很快。

2.按位操作

每次和1相与,然后判断是1 or 0,然后n右移一位,继续直到n变为0.

更新:

3.位操作技巧

相比于2去判断每一位,我们可以通过让 n&n-1来实现1的个数计数。

n-1 的二进制表示是n的最后一个1表示变成0,那个1表示之后的0都变成1。

那么n-1&n 就是在那个1之前的所有数都保留,那个1以及它之后的数都变成0。

1次n-1&n的操作,让我们将n的最后一个1变成了0,也说明这有一个1,直到n-1&n 为0的时候,我们就直到所有1的处理完毕了。

对于方法2,时间复杂度是O(1),为第一个1到最后一个1的位数长度。

对于此方法,时间复杂度也是O(1),为1的个数。

就leetcode跑了几次来说,方法1,2差不多,都在16或者20ms,方法3能到12ms。

更多leetcode算法题解法: 专栏 leetcode算法从零到结束

三.源码

1.粗暴

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        n = bin(n)[2:]
        return sum([1 for i in n if i=='1'])

2.按位操作

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        cnt=0
        while n & 0xffffffff:
            cnt+=n&1==1
            n=n>>1
        return cnt
发布了218 篇原创文章 · 获赞 191 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/CSerwangjun/article/details/103249219