8. String to Integer (atoi)

Posted 积少成多

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了8. 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.

Update (2015-02-10):
The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button  to reset your code definition.

===============

string变int,字符串转化为int

关键的地方是:

1,什么合法的数字字符串

2,字符串开头可以有空白符

3,字符串第一个字符可以是+,-,也可以没有正负号

4,整数溢出的处理方法?

  只比较n和MAX_INT/10的大小,

  即,若n>MAX_INT/10时,说明最后一步转换时,n*10一定大于MAX_INT,所以当得知n>MAX_INT/10,直接return MAX_INT

  若n==MAX_INT/10,那么比较最后一个数字c与MAX_INT%10的大小,如果n==MAX_INT/10 && c>MAX_INT%10,return MAX_INT

代码实现:

class Solution {
public:
    int myAtoi(string str) {
        int num = 0;
        int sign = 1;
        const int n = str.length();
        int i = 0;
        while(i<n && str[i]== ) i++;

        if(str[i] == +){
            i++;
        }else if(str[i]==-){
            sign = -1;
            i++;
        }
        for(;i<n;i++){
            if(!isdigit(str[i])) break;
            if(num > INT_MAX/10 ||
                (num==INT_MAX/10 && (str[i]-0)>INT_MAX%10)){
                return sign==-1? INT_MIN:INT_MAX;
            }
            num = num*10+str[i]-0;
        }
        return num*sign;
    }
};

 

以上是关于8. String to Integer (atoi)的主要内容,如果未能解决你的问题,请参考以下文章

8. String to Integer (atoi)

8. String to Integer (atoi)

8. String to Integer (atoi)

8 String to Integer (atoi)

LeetCode - 8 - String to Integer (atoi)

leetcode-8. String to Integer (atoi)