[LeetCode] Challenge log 191

191. Number of 1 Bits

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

Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.

Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
# normal solution O(log n) = O(32) = O(1), since n = 32 bits
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0: return 0
count = 1
while (n>1):
if n % 2 == 1: count += 1
n = n // 2
return count
1
2
3
4
5
6
7
8
9
10
11
12
# bit operation trick O(1)
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
while n != 0:
n = n & n-1
count += 1
return count
1
2
3
4
5
6
7
8
# built-in function (cheating)
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
return bin(n).count('1')
Python bit operation:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
a = 60            # 60 = 0011 1100 
b = 13 # 13 = 0000 1101
c = 0

c = a & b; # 12 = 0000 1100
print "Line 1 - Value of c is ", c

c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c

c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c

c = ~a; # -61 = 1100 0011
print "Line 4 - Value of c is ", c

c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c

c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c
0%