Advertisement
Guest User

Untitled

a guest
May 23rd, 2019
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. def hammingWeight(self, n):
  2. nstr = '{0:32b}'.format(n)
  3. count = 0
  4. for x in nstr:
  5. if x == "1":
  6. count += 1
  7.  
  8. return count
  9.  
  10. """
  11. The above arrows point to positions where the corresponding bits are different.
  12.  
  13.  
  14.  
  15. Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).
  16.  
  17. Example 1:
  18. Input: 00000000000000000000000000001011
  19. Output: 3
  20. Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
  21. Example 2:
  22. Input: 00000000000000000000000010000000
  23. Output: 1
  24. Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
  25. Example 3:
  26. Input: 11111111111111111111111111111101
  27. Output: 31
  28. Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
  29.  
  30. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement