Skip to content

Commit bab8a47

Browse files
committed
Reverse Bits/ Number of 1 Bits
1 parent e592860 commit bab8a47

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

190 Reverse Bits.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
'''
2+
Reverse bits of a given 32 bits unsigned integer.
3+
4+
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
5+
6+
Follow up:
7+
If this function is called many times, how would you optimize it?
8+
'''
9+
10+
class Solution(object):
11+
def reverseBits(self, n):
12+
"""
13+
:type n: int
14+
:rtype: int
15+
"""
16+
n = ((n & 0x55555555) << 1) | ((n >> 1) & 0x55555555)
17+
n = ((n & 0x33333333) << 2) | ((n >> 2) & 0x33333333)
18+
n = ((n & 0x0f0f0f0f) << 4) | ((n >> 4) & 0x0f0f0f0f)
19+
n = (n << 24) | ((n & 0xff00) << 8) | ((n >> 8) & 0xff00) | (n >> 24)
20+
return n & 0xffffffff
21+
22+
23+
if __name__ == "__main__":
24+
assert Solution().reverseBits(43261596) == 964176192

191 Number of 1 Bits.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
'''
2+
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
3+
4+
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
5+
'''
6+
7+
class Solution(object):
8+
def hammingWeight(self, n):
9+
"""
10+
:type n: int
11+
:rtype: int
12+
"""
13+
n -= (n >> 1) & 0x55555555
14+
n = (n & 0x33333333) + ((n >> 2) & 0x33333333)
15+
n = (n + (n >> 4)) & 0x0f0f0f0f
16+
n += (n >> 8)
17+
n += (n >> 16)
18+
return n & 0x3f
19+
20+
21+
if __name__ == "__main__":
22+
assert Solution().hammingWeight(4294967295) == 32
23+
assert Solution().hammingWeight(11) == 3

0 commit comments

Comments
 (0)