The title

Write a function that takes an unsigned integer as an input (in the form of a binary string) and returns the number of digits ‘1’ in its binary expression (also known as hamming weight).

 

Tip:

Note that in some languages, such as Java, there are no unsigned integer types. In this case, both input and output will be specified as signed integer types, and should not affect your implementation, because the internal binary representation of an integer is the same whether it is signed or unsigned. In Java, the compiler uses binary complement notation to represent signed integers. Therefore, in example 3 above, the input represents the signed integer -3.

Example 1: input, output: 00000000000000000000000000001011 3 explain: the input binary string in 00000000000000000000000000001011, a total of three for the '1'. Example 2: input: 00000000000000000000000010000000 output: 1: input binary string in 00000000000000000000000010000000, a total of a '1'. Example 3: input, output: 11111111111111111111111111111101 31 explanation: input binary string in 11111111111111111111111111111101, a total of 31 as' 1 '.Copy the code

Tip:

The input must be a binary string of length 32.

Advanced:

How would you optimize your algorithm if you called this function multiple times?

Their thinking

class Solution: def hammingWeight(self, n: int) -> int: StrI = bin (n) # # into binary print (n, strI) return strI. Count (" 1 ") if __name__ = = "__main__" : nums = 11111111111111111111111111111101 result = Solution().hammingWeight(nums) print(result)Copy the code