Skip to content

Commit 82660f2

Browse files
committed
Adding Efficient Solution - Problem - 191 - Number of 1 bits
1 parent ef6b18f commit 82660f2

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Number_of_1_bits/EfficientSolution.py

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+

0 commit comments

Comments
 (0)