File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
Expand file tree Collapse file tree 1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change 1+ ##==================================
2+ ## Leetcode
3+ ## Student: Vandit Jyotindra Gajjar
4+ ## Year: 2020
5+ ## Problem: 191
6+ ## Problem Name: Number of 1 Bits
7+ ##===================================
8+ #
9+ #Write a function that takes an unsigned integer and return the number of '1' bits it has
10+ #(also known as the Hamming weight).
11+ #
12+ #Example 1:
13+ #
14+ #Input: 00000000000000000000000000001011
15+ #Output: 3
16+ #Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
17+ #Example 2:
18+ #
19+ #Input: 00000000000000000000000010000000
20+ #Output: 1
21+ #Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
22+ #Example 3:
23+ #
24+ #Input: 11111111111111111111111111111101
25+ #Output: 31
26+ #Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
27+ from collections import Counter as c #Import Counter module
28+ class Solution :
29+ def hammingWeight (self , n ):
30+ tmp = "{:032b}" .format (n ) #Initialize tmp and find binary representation
31+ tmpCount = c (tmp ) #Initialize tmpCount and use Counter for tmp
32+ for key , val in tmpCount .items (): #Loop through tmpCount
33+ if key == '1' : #Condition-check: If we find '1' bit
34+ return val #Return value for key == '1'
35+ return 0 #Otherwise return 0
36+
You can’t perform that action at this time.
0 commit comments