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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章