-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: convert str to int and vice-versa
- Loading branch information
1 parent
94a9c65
commit 735c5a8
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
# Question: Implement a string to integer and vice versa converter | ||
# without using int function | ||
|
||
|
||
def convertToStr(n): | ||
ret = [] | ||
if n == 0: | ||
return "0" | ||
neg = False | ||
if n < 0: | ||
neg = True | ||
n *= -1 | ||
while n: | ||
x = n % 10 | ||
ret.append(chr(48 + x)) | ||
n //= 10 | ||
|
||
return ("-" if neg else "") + "".join(ret[::-1]) | ||
|
||
|
||
def convertToInt(s): | ||
ret = 0 | ||
neg = False | ||
for c in s: | ||
if c == "-": | ||
neg = True | ||
else: | ||
ret *= 10 | ||
ret += ord(c) - 48 | ||
|
||
return ret * (-1 if neg else 1) | ||
|
||
|
||
print("Convert to STR: " + convertToStr(-500)) | ||
|
||
print("Convert to INT: " + str(convertToInt("-500") + 10)) |