LeetCode-8. String to Integer (atoi)(字符串转换整数)

问题:请你来实现一个 atoi 函数,使其能将字符串转换成整数。

首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。

当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号;假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。

该字符串除了有效的整数部分之后也可能会存在多余的字符,这些字符可以被忽略,它们对于函数不应该造成影响。

注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换。

在任何情况下,若函数不能进行有效的转换时,请返回 0。

说明:

假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为 [−2的31次方,  2的31次方 − 1]。如果数值超过这个范围,请返回  INT_MAX (2的31次方 − 1) 或 INT_MIN (−2的31次方) 。

Example 1:

Input: "42"
Output: 42

Example 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.

Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.

方法一:分类讨论

这道题其实考察的是对字符串的处理,真正在循环部分没什么特别的。首先就是排除空字符串情况,然后对非空字符串的第一个字符再进行讨论。第一个字符为空格,则跳过所有连续空格,如果发现字符串全为空格,则返回0。跳过空格后,若第一个字符为‘+’ 或者 ‘-’,则保留这个符号。首字符若是其它情况,那返回0,但这种情况不方便单独讨论,只能放在循环中统一处理。这里要注意的是,返回的结果是字符串中一段连续数字字符,不是所有数字字符组合在一起的情况。时间复杂度是O(n)。

#Python
class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        if len(str) == 0:    #字符串为空
            return 0
        
        i = 0
        while i < len(str) and str[i] == ' ':    #非空字符串跳过空格符
            i = i + 1
        if i == len(str):    #如果所有都是空格,返回0
            return 0
        
        sign = 1    #在没有'+'或者'-'的情况下默认为'+'
        if str[i] == '+' or str[i] == '-':    #非空首字符是符号的情况
            sign = 1 if str[i] == '+' else -1
            i = i + 1
            
        num = 0
        MAX = 2**31 - 1;MIN = -2**31
        for j in range(i,len(str)):    #当前首字符是数字或者其它情况
            if not str[j].isdigit(): #一旦出现非数字的字符,循环终止,返回结果,因为num初值为0,所以这里也处理了首字符是非数字的情况
                break
            num = num*10 + (ord(str[j])-ord('0'))
            if num > MAX:
                return MAX if sign == 1 else MIN
        return sign * num
//C++
class Solution {
public:
    int myAtoi(string str) {
        int l = str.length();
        if(l == 0) return 0;    //判断字符串是否为空
        
        int i = 0;
        while(i < l && str[i] == ' ') i = i + 1;    //跳过所有空格
        if(i == l) return 0;
        
        bool sign = true;    //C++的条件语句没有Python那么灵活,为便于后面的条件判断,这里用bool值来判定正负号
        if(str[i] == '+' || str[i] == '-') {    //第一个非空字符为符号的情况
            sign = (str[i] == '+');    //如果为'+',那么sign为true
            i = i + 1;
        }
        
        int temp =0, num = 0;
        for(;i < l;i ++){    //其它所有情况
            if(!isdigit(str[i])) break;    //如果不是数字,跳出循环
            num = num * 10 + (str[i] - '0');    
            if (num / 10 != temp)    //跟Python不同,C++数字一旦超出界限,则该数字不再按超出的那个数字表示,因此除以10后与它的上一个数字肯定不同
                return sign ? INT_MAX : INT_MIN;    //C++中有现成的最大最小值,不需要额外定义
            temp = num; 
        }
        return sign ? num:-num;
    }
};

猜你喜欢

转载自blog.csdn.net/theShepherd/article/details/86509684
今日推荐