8. String to Integer[M]字符串转整数

题目


Inplement atoi which converts a string to an integer.
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.
Note:

  • Only the space character ' ' is considered as whitespace character.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [ (−2^{31}, 2^{31} − 1) ]. If the numerical value is out of the range of representable values, INT_MAX ( (2^{31} − 1) ) or INT_MIN ( (−2^{31}) ) is returned.

思路


思路1

问题的关键在于必须满足各种条件:

  • 开头的空格
  • 正负号的处理
  • 溢出判断
  • 数字的处理

思路2:正则表达式(Python)

  • str.strip(rm) 删除str字符中开头和结尾处,位于rm序列的字符
  • str.lstrip(rm) 删除str字符中开头处,位于rm序列的字符
  • str.rstrip(rm) 删除str字符中结尾处,位于rm序列的字符
  • 利用try-except块来检查异常输入
  • 正则表达式,re模块
    d 表示[0,9]的数字,d+ 表示不止一个数字
    ^ 表示匹配字符串的开头
    -?表示匹配前一个字符或子表达式0次或1次重复
    re.search 扫描整个字符串并返回第一个成功的匹配,匹配成功返回一个匹配的对象,否则返回None
    group() 分组就是用()括起来的正则表达式,匹配出的内容表示一个分组。group()输出一个包含这个组所对应的元组。

cpp

class Solution {
public:
    int myAtoi(string str) {
        
        int p=0;
        while(str[p]==' '){
            p++;
        }
        
        int sign=1;//判断正负
        if(str[p]=='+'){
            p++;
        }
        else if(str[p]=='-'){
            sign=-1;
            p++;
        }
        
        long resInt=0;
        for(int i=p;i<str.size();i++){
            if(str[i]< '0' || str[i]> '9'){
                break;
            }
            int temp=str[i]-'0';//转化为数字
            resInt = 10*resInt+temp;
            if(sign==1){
                if(resInt >= INT_MAX){
                    return INT_MAX;
                }
            }
            else{
                 if(resInt-1 >= INT_MAX){
                    return INT_MIN;
                }
            }
        }
        resInt = sign*resInt;
        return resInt;
    }
    
};

Python

class Solution(object):
    def myAtoi(self, str):
        """
        :type str: str
        :rtype: int
        """
        str = str.strip()
        try:
            res = int(re.search('(^[+-]?d+)', str).group())
        except:
            res = 0
        return min(max(-2147483648, res), 2147483647)
原文地址:https://www.cnblogs.com/Jessey-Ge/p/10993437.html