forked from dsrao711/DSA-Together-HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Count1s.py
59 lines (37 loc) · 861 Bytes
/
Count1s.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#
# Approach 1
class Solution:
def setBits(self, n):
# Keep counting until n is 1
count = 0
while(n):
count += n&1
n >>= 1
return count
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
T=int(input())
for i in range(T):
N = int(input())
ob = Solution()
ans = ob.setBits(N)
print(ans)
# } Driver Code Ends
# Approach 2 - Use python inbuilt bin() function
class Solution:
def setBits(self, n):
# code here
return bin(N).count('1')
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
T=int(input())
for i in range(T):
N = int(input())
ob = Solution()
ans = ob.setBits(N)
print(ans)
# } Driver Code Ends