不使用int()将String转换为Int

时间:2014-07-04 02:41:05

标签: python python-3.x

我尝试在Python中实现add2stringssub2stringsmult2strings函数。如果你只是做int(string),他们就会非常容易,但我想在没有这个的情况下做到这一点,而不会导入像Decimal这样的另一个作弊行为。我目前的想法是使用bytes

还有其他办法吗?

3 个答案:

答案 0 :(得分:10)

请参阅C:

中的基本atoi
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;
}

转换为Python:

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

    return rtr

测试它:

>>> atoi('123456789')
123456789   

如果您希望以int的方式容纳可选符号和空格:

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

现在添加例外,你就在那里!

答案 1 :(得分:2)

这实在是效率不高但是:

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

这稍微好一些:

>>>> 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 :(得分:1)

What about just iterating through all the integers, converting them to strings and comparing 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")

这给出了:

"-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