Convert String to Int without int ()

I am trying to implement add2strings , sub2strings , mult2strings in Python. They are very easy if you just do int(string) , but I want to do them without it and without importing another fraudulent thing like Decimal . My current idea is to use bytes .

Is there any other way to do this?

+6
source share
3 answers

Refer to the base atoi in C:

 int myAtoi(char *str) { int res = 0; // Initialize result // Iterate through all characters of input string and update result for (int i = 0; str[i] != '\0'; ++i) res = res*10 + str[i] - '0'; // return result. return res; } 

What translates to Python:

 def atoi(s): rtr=0 for c in s: rtr=rtr*10 + ord(c) - ord('0') return rtr 

Check this:

 >>> atoi('123456789') 123456789 

If you want to place an optional character and space, as int does:

 def atoi(s): rtr, sign=0, 1 s=s.strip() if s[0] in '+-': sc, s=s[0], s[1:] if sc=='-': sign=-1 for c in s: rtr=rtr*10 + ord(c) - ord('0') return sign*rtr 

Now add the exceptions and you are there!

+9
source

This is really inefficient, but:

 >>> zero = ord("0") >>> s = "1234" >>> sum([x * 10**i for i, x in enumerate(map(lambda x: x - zero, map(ord, s))[::-1])]) 1234 

This is a little better:

 >>>> sum([x * 10**i for i, x in enumerate([ord(x) - zero for x in s[::-1]])]) 1234 >>> atoi = lambda s: sum([x * 10**i for i, x in enumerate([ord(x) - zero for x in s[::-1]])]) >>> atoi("1234") 1234 
+2
source

How to simply iterate over all integers, convert them to strings and compare strings?

 import exceptions MAX_INT = 1000 MIN_INT = -1000 def str2int(s): for i in range(MIN_INT,MAX_INT): if s == str(i): return i raise exceptions.OverflowError def add2strings(s,t): return str(str2int(s)+str2int(t)) print add2strings("170","-300") print add2strings("170","-1001") 

This gives:

 "-170" Traceback (most recent call last): Line 15, in <module>  print add2strings("170","-1001") Line 12, in add2strings  return str(str2int(s)+str2int(t)) Line 9, in str2int  raise exceptions.OverflowError OverflowError 
+1
source

Source: https://habr.com/ru/post/971739/


All Articles