Skip to content

Commit b48f8fd

Browse files
committed
Added snippet to reverse bits of an integer
1 parent 5f697c4 commit b48f8fd

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Reverse bits of an integer
2+
*tags:* **bit manipulation, python**
3+
4+
5+
**Snippet**
6+
```python
7+
8+
def reverseBits(n):
9+
# Initially all bits are zero
10+
reverseInt = 0
11+
# Size of int is 32 bits
12+
for bitPos in range(32):
13+
# Check if bit at position "bitPos" is 1,
14+
# If that bit is 0, then we don't need to add
15+
# it to reverseInt since it won't make a difference
16+
if n & (1 << bitPos):
17+
# Change bit at "bitPos" to 1
18+
reverseInt = reverseInt | (1 << (31-bitPos))
19+
20+
return revAns
21+
22+
print(reverseBits(10))
23+
24+
```

0 commit comments

Comments
 (0)