Skip to content

Commit 8f1b1f9

Browse files
author
Ahmed, Mehtab
committed
Added function to reverse a 32 bit signed int
1 parent 9629aef commit 8f1b1f9

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

reverse32bitsignedint.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# reverse a 32 bit signed int
2+
# if ans overflows then returns 0
3+
def reverse32bitsignedint(n):
4+
is_negative = 0
5+
if n < 0:
6+
is_negative = 1
7+
n = -n
8+
ans = 0
9+
while n:
10+
quotient = n // 10
11+
reminder = n % 10
12+
n = quotient
13+
ans = ans * 10 + reminder
14+
limit = 1 << 31
15+
if is_negative:
16+
ans = -ans
17+
if (ans <= -limit) or (ans >= limit - 1):
18+
return 0
19+
return ans

0 commit comments

Comments
 (0)