Tuesday, August 25, 2015

Leetcode 191. Number of 1 Bits

https://leetcode.com/problems/number-of-1-bits/

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 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 cnt
Run Time: 48 ms

No comments:

Post a Comment