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 resultRun Time: 56 ms
Solution 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 cntRun Time: 48 ms
No comments:
Post a Comment