Skip to content

Commit 5986d54

Browse files
committed
feat(strings): string to integer v2
1 parent 0bbeded commit 5986d54

File tree

2 files changed

+72
-1
lines changed

2 files changed

+72
-1
lines changed

pystrings/strtoint/__init__.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,23 @@ def str_to_int(input_str: str) -> int:
2424
output_int += number
2525

2626
return output_int *-1 if is_negative else output_int
27+
28+
def str_to_int_v2(input_str: str) -> int:
29+
output_int = 0
30+
31+
if input_str[0] == '-':
32+
start_idx = 1
33+
is_negative = True
34+
else:
35+
start_idx = 0
36+
is_negative = False
37+
38+
for i in range(start_idx, len(input_str)):
39+
place = 10**(len(input_str) - (i+1))
40+
digit = ord(input_str[i]) - ord('0')
41+
output_int += place * digit
42+
43+
if is_negative:
44+
return -1 * output_int
45+
else:
46+
return output_int

pystrings/strtoint/test_string_to_int.py

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import unittest
2-
from . import str_to_int
2+
from . import str_to_int, str_to_int_v2
33

44

55
class StrToIntTestCases(unittest.TestCase):
@@ -53,5 +53,56 @@ def test_7(self):
5353
self.assertEqual(expected, actual)
5454

5555

56+
class StrToIntV2TestCases(unittest.TestCase):
57+
def test_1(self):
58+
"""should convert '123' to 123"""
59+
input_str = "123"
60+
expected = 123
61+
actual = str_to_int_v2(input_str)
62+
self.assertEqual(expected, actual)
63+
64+
def test_2(self):
65+
"""should convert '-12332' to -12332"""
66+
input_str = "-12332"
67+
expected = -12332
68+
actual = str_to_int_v2(input_str)
69+
self.assertEqual(expected, actual)
70+
71+
def test_3(self):
72+
"""should convert '554' to 554"""
73+
input_str = "554"
74+
expected = 554
75+
actual = str_to_int_v2(input_str)
76+
self.assertEqual(expected, actual)
77+
78+
def test_4(self):
79+
"""should convert '0' to 0"""
80+
input_str = "0"
81+
expected = 0
82+
actual = str_to_int_v2(input_str)
83+
self.assertEqual(expected, actual)
84+
85+
def test_5(self):
86+
"""should convert '-1293' to -1293"""
87+
input_str = "-1293"
88+
expected = -1293
89+
actual = str_to_int_v2(input_str)
90+
self.assertEqual(expected, actual)
91+
92+
def test_6(self):
93+
"""should convert '529' to 529"""
94+
input_str = "529"
95+
expected = 529
96+
actual = str_to_int_v2(input_str)
97+
self.assertEqual(expected, actual)
98+
99+
def test_7(self):
100+
"""should convert '-999' to -999"""
101+
input_str = "-999"
102+
expected = -999
103+
actual = str_to_int_v2(input_str)
104+
self.assertEqual(expected, actual)
105+
106+
56107
if __name__ == '__main__':
57108
unittest.main()

0 commit comments

Comments
 (0)