forked from MTrajK/coding-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_integer.py
More file actions
55 lines (39 loc) · 847 Bytes
/
reverse_integer.py
File metadata and controls
55 lines (39 loc) · 847 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'''
Reverse Integer
Given signed integer, reverse digits of an integer.
Input: 123
Output: 321
Input: -123
Output: -321
Input: 120
Output: 21
=========================================
Simple solution, mod 10 to find all digits.
Time Complexity: O(N) , N = number of digits
Space Complexity: O(1)
'''
############
# Solution #
############
def reverse_integer(x):
if x == 0:
return 0
sign = x // abs(x) # find the sign, -1 or 1
x *= sign # make positive x, or x = abs(x)
res = 0
while x > 0:
res = (res * 10) + (x % 10)
x //= 10
return res * sign
###########
# Testing #
###########
# Test 1
# Correct result => 321
print(reverse_integer(123))
# Test 2
# Correct result => -321
print(reverse_integer(-123))
# Test 3
# Correct result => 21
print(reverse_integer(120))