不使用 int() 将 String 转换为 Int [英] Convert String to Int without int()

查看:64
本文介绍了不使用 int() 将 String 转换为 Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Python 中实现 add2stringssub2stringsmult2strings 函数.如果您只执行 int(string),它们都非常简单,但我想在没有这些的情况下执行它们,并且不导入另一个作弊的东西,例如 Decimal.我目前的想法是使用bytes.

还有其他方法可以做到这一点吗?

解决方案

参考一个基本的atoi C:

int myAtoi(char *str){int res = 0;//初始化结果//遍历输入字符串的所有字符并更新结果for (int i = 0; str[i] != '\0'; ++i)res = res*10 + str[i] - '0';//返回结果.返回资源;}

翻译成 Python:

def atoi(s):时间=0对于 c in s:rtr=rtr*10 + ord(c) - ord('0')返回

测试一下:

<预><代码>>>>atoi('123456789')123456789

如果你想以 int 的方式容纳一个可选的符号和空格:

def atoi(s):rtr, 符号=0, 1s=s.strip()如果 s[0] 在 '+-':sc, s=s[0], s[1:]如果 sc=='-':符号=-1对于 c in s:rtr=rtr*10 + ord(c) - ord('0')返回符号*rtr

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

I'm trying to implement add2strings, sub2strings, mult2strings functions in Python. 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. My current idea is to use bytes.

Is there another way to do this?

解决方案

Refer to a basic 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;
}

Which translates into the 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:

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!

这篇关于不使用 int() 将 String 转换为 Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆