Skip to content

Commit

Permalink
feat: convert str to int and vice-versa
Browse files Browse the repository at this point in the history
  • Loading branch information
ashwin-nair98 committed Mar 6, 2024
1 parent 94a9c65 commit 735c5a8
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions elements/6_1_Integer_String_Converter/solution.py
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))

0 comments on commit 735c5a8

Please sign in to comment.