简体   繁体   English

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

[英]Convert String to Int without int()

I'm trying to implement add2strings , sub2strings , mult2strings functions in Python. 我正在尝试在Python中实现add2stringssub2stringsmult2strings函数。 They're all very easy if you just do int(string) , but I want to do them without that and without importing another cheating thing like Decimal . 如果你只是做int(string) ,它们都很容易,但我想在没有它的情况下完成它们而不导入像Decimal那样的另一个作弊行为。 My current idea is to use bytes . 我目前的想法是使用bytes

Is there another way to do this? 还有另一种方法吗?

Refer to a basic atoi in C: 参考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;
}

Which translates into the Python: 这转化为Python:

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

    return rtr

Test it: 测试一下:

>>> atoi('123456789')
123456789   

If you want to accommodate an optional sign and whitespace the way that int does: 如果你想以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

Now add exceptions and you are there! 现在添加例外,你就在那里!

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM