atoi函数实现

来源:互联网 发布:淘宝装修代码在线生成 编辑:程序博客网 时间:2024/06/06 02:41

对应leetcode: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.不规则输入,但是有效。"-3924"."+20"

2.无效格式,"++c","++1"

3.溢出数据,"2147483648"

class Solution {public:    int myAtoi(string str) {        int num = 0;        int sign = 1;        const int n = str.length();        int i = 0;                while(str[i]==' '&&i<n) i++;                if(str[i]=='+')            i++;        else if(str[i]=='-'){            sign = -1;            i++;        }        for(;i<n;i++){            if(str[i]<'0'||str[i]>'9')                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;    }};


0 0
原创粉丝点击