AlgoDesign

Interconvert string and integer

1from functools import reduce
2import string
3class Solution:
4    def intToStr(self, num):
5        neg = False
6        if int < 0:
7            num = -num
8            neg = True
9
10        res = ""
11        while num > 0:
12            n = num % 10
13            res.append(chr(ord("0") + n))
14            num //= 10
15        res = res[::-1]
16
17        if neg: return "-" + res
18        return res
19    
20    def strToInt1(self, s):
21        if len(s) == 0: return 0
22        neg, start = False, 0
23        if s[0] == "-":
24            neg = True
25            start = start + 1
26
27        res = 0
28        for i in range(start, len(s)):
29            res *= 10
30            res += int(s[i])
31
32        if neg: return "-" + res
33        return res
34    
35    def strToInt2(self, s):
36        res = reduce(lambda runningSum, c: (runningSum * 10) + string.digits.index(c), s[s[0] in "+-":], 0)
37        if s[0] == "-": return -res
38        return res