-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathstring_integer_interconversion.py
82 lines (63 loc) · 1.48 KB
/
string_integer_interconversion.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"""
Integer to String
"""
def single_digit_to_char(digit):
return chr(ord('0')+digit)
def int_to_string(x: int):
if x == 0:
return "0"
is_neg = False
if x < 0:
is_neg, x = True, -x
result = []
while x > 0:
digit = x % 10
result.append(single_digit_to_char(digit))
x = x // 10
if is_neg:
result.append('-')
return "".join(reversed(result))
"""
String to Integer
"""
def single_char_to_int(character):
# num_mapping = {
# "1": 1,
# "2": 2,
# "3": 3,
# "4": 4,
# "5": 5,
# "6": 6,
# "7": 7,
# "8": 8,
# "9": 9,
# "0": 0,
# }
# return num_mapping[character]
return ord(character) - ord('0')
def string_to_int(s: str):
is_neg = False
num = 0
multiplier = 1
start_idx = 0
if s and s[0] == "-":
is_neg, start_idx = True, 1
if s and s[0] == "+":
start_idx = 1
for idx in range(start_idx, len(s)):
# for idx in range(start_idx, len(s)):
num *= 10
num += single_char_to_int(s[idx]) # *multiplier
# multiplier *= 10
if is_neg:
return -num
return num
print(string_to_int("22"), type(string_to_int("22")))
print(string_to_int("1001"))
print(string_to_int("210"))
print(string_to_int("012"))
print(string_to_int("23"))
print(string_to_int("-2"))
print(string_to_int("34567"))
print(string_to_int("343434"))
print(string_to_int("+7654345"))