Two solutions.
Solution 1:
# T:O(m) S:O(1)
class Solution:
# @param n, an integer
# @return an integer
def hammingWeight(self, n):
result = 0
while n:
n &= n - 1
result += 1
return result
Run Time: 56 msSolution 2:
# T:O(m) S:O(m)
class Solution:
# @param n, an integer
# @return an integer
def hammingWeight(self, n):
s = bin(n)[2:]
cnt = 0
for ch in s:
if ch == '1':
cnt += 1
return cnt
Run Time: 48 ms
No comments:
Post a Comment