leetcode 191. Number of 1 Bits Detailed python3

I. Description of the problem

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?

II. Problem-solving ideas

1. brutal methods

bin (num) num direct view of the binary, then iterates each character, judgment is not 1, then it is counter +1 course quickly.

2. Press-bit operating

And each phase 1, and then judgment is 0 or 1, and n right one, continues until n becomes 0.

Update:

3. Bit operating skills

As compared to 2 to judge each one, we may be implemented by having the counted number 1 n & n-1.

n-1 is the binary representation of the last n represents 1 becomes 0, 0 after 1 shows that have become 1.

Then the n-1 & n is the number of all previous 1 remain in that, the number 1 and then it turned into 0.

1 n-1 & n operation, so that we will be n the last 1 becomes 0, also shows that there is a 1, until the n-1 & n is 0, we will until all processing 1 is completed.

For the method 2, the time complexity is O (1), the length of the first to the last digit is a 1.

For this method, time complexity is O (1), the number of 1s.

Leetcode to run several times, a method similar to 1,2, or 16 are 20ms, the method can be 3 to 12ms.

More leetcode algorithm problem solution: Columns  leetcode algorithm from zero to the end

III. Source

1. rude

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. Press-bit operating

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万+

Guess you like

Origin blog.csdn.net/CSerwangjun/article/details/103249219