A Python solution with some speed tricks


  • 3
    A
    class Solution:
        # @param n, an integer
        # @return an integer
    	def hammingWeight(self, n):
    		bitsMap = [0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4]
    		i = 0
    		result = 0
    		while i < 32:
    			result += bitsMap[(n>>i) & 15]
    			i += 4
    		return result
    

    I map a number in [0,15] to its number of '1' bits, and the 'while' cope with 4 bits rather than 1 bits at a time, which means it will be faster.


Log in to reply
 

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