JonnyF--String to Integer (atoi)

Implement atoi to convert a string to an integer.

Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

解题思路:

       这道题是将字符窜转换成数字,因此只需要主要下面几点就好了。
       1.数字前面有空格 如s=“    123456”
       2.数字前出现了不必要或多于的字符导致数字认证错误,输出0   如s=“   b1234”  ,s=“  ++1233” , s=“ +-1121”
       3.数字中出现了不必要的字符,返回字符前的数字 如s=“   12a12” , s=“ 123  123”
       4.数字越界 超过了范围(-2147483648--2147483647) 若超过了负数的 输出-2147483648  超过了正数的输出2147483647

复制代码
class Solution:
    # @param str, a string
    # @return an integer
    def myAtoi(self, str):
        if str == '':
            return(0)
        str = list(str)
        result = []
        positive = negtive = 0
        has_digit = False
        for i in range(len(str)):
            if str[i] != '-' and str[i] != '+' and str[i].isdigit() == False and str[i] != ' ':
                if has_digit is False:
                    return(0)
                else:
                    break
            if str[i] == ' ' and has_digit:
                break
            if str[i] == ' ' and (negtive or positive):
                return(0)
            if str[i] == '-':
                negtive = negtive + 1
            if str[i] == '+':
                positive = positive + 1
            if negtive > 1 or positive > 1 or (negtive == 1 and positive == 1):
                return(0)
            if str[i].isdigit():
                has_digit = True
                result.append(str[i])
        result = ''.join(result)
        if negtive:
            result = '-' + result
        if has_digit:
            if int(result) > 2**31 - 1:
                return(2147483647)
            if int(result) < -2**31:
                return(-2**31)
            return(int(result))
        else:
            return(0)
复制代码
posted @   F-happy  阅读(101)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示