4 Lines Python AC Solution Beats 100%


  • 0

    It's fast because using bit-manipulation. Algorithm is O(logn), because each input n has number of logn binary digits.

    In the while loop:
    n shift 1 position right until become zero
    if 2^0 == 1: count +1

    class Solution(object):
        def hammingWeight(self, n):
            if n < 0: return bin(n).count('1')        # correction according to Jun_Tang
            count = 0
            while n > 0:
                count, n = count+(n&1), n>>1
            return count
    

  • 0
    J

    i wonder if this solution would for negative numbers.


  • 0

    @Jun_Tang Thanks for your correction! Codes are updated, but sadly, the performance dropped from 39ms to 45ms. Wondering that why there's no negative numbers in test cases.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.