LeetCode.8.String to Integer (atoi)

本文介绍了一个将字符串转换为整数的功能实现方法,包括处理正负号、非数字字符及边界条件等细节。提供了Python和C++两种语言的具体实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接: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.

Requirements for atoi:

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.

注意以下要点:

  • 字符串为空或者全是空格,返回0;
  • 字符串的前缀空格忽略;
  • (忽略空格之后)遇到的第一个字符,如果是‘+’或‘-’号,继续往后读,进入处理数字的阶段;如果第一个字符是数字,则进入处理数字的阶段;如果不是前面的2种,返回0;
  • 处理数字的过程中,如果字符为非数字,就停止转换,返回当前值;
  • 如果超过了int值的范围,那么返回 INT_MAX (2147483647) 或者 INT_MIN (-2147483648)。

Python

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        if not str:
            return 0
        str = str.strip()
        sign = 1
        if str[0] == "+" or str[0] == "-":
            if len(str) == 1:
                return 0
            if not str[1].isdigit():
                return 0
        res = 0
        for n in str:
            if n == "-":
                sign = -1
                continue
            if n == "+":
                sign = 1
                continue
            if n.isdigit():
                res = res * 10 + sign * (ord(n)-ord("0"))
            else:
                break
        if res > 2147483647:
            return 2147483647
        elif res < -2147483648:
            return -2147483648
        else:
            return res

C++

class Solution {
public:
    int myAtoi(string str) {
        if (str == "")
           return 0;  

        int i = 0;  
        while (str[i] != '\0' && str[i] == ' ')  
          ++i;  

        if (str[i] == '\0')  
          return 0;  //空字符串

        int sign = 1;  

        if (str[i] == '+')  
        {  
            sign = 1;  
            ++i;  
        }  
        else if (str[i] == '-')  
        {  
            sign = -1;  
            ++i;  
        } //正负号标记

        long long sum = 0;  
        while (str[i] != '\0')  
        {  
            if (str[i] >= '0' && str[i] <= '9')  
                sum = sum * 10 + sign * (str[i] - '0');  
            else   
                return sum;  
            if (sum > INT_MAX || sum < INT_MIN)   
                return sum > 0 ? INT_MAX : INT_MIN;  //溢出处理
            ++i;  
        }  
        return sum;  
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值