LeetCode#8 String to Integer (atoi)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Acmer_Sly/article/details/75213679

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 returne

题目的要求:
1. 首先需要丢弃字符串前面的空格;
2. 然后可能有正负号(注意只取一个,如果有多个正负号,那么说这个字符串是无法转换的,返回0。比如测试用例里就有个“+-2”);
3. 字符串可以包含0~9以外的字符,如果遇到非数字字符,那么只取该字符之前的部分,如“-00123a66”返回为“-123”;
4. 如果超出int的范围,返回边界值(2147483647或-2147483648)。
弄懂了题目的意思,就是一个简单的模拟了!

class Solution {
public:
    int myAtoi(string str) {
        long int ans;           //用long int可以装下最大的int类型的数
        int i=0,j;
        int len=str.length();
        if(str.empty())return 0;
        int flag=0;
        while(i<len)
        {
            if((str[i]<='9'&&str[i]>='0')||str[i]=='+'||str[i]=='-')break;
            else if(str[i]==' ');
            else return 0;
            i++;
        }
        if(i>=len)return 0;
        if(str[i]=='-'){
            i++;
            flag=1;
        }
        else if(str[i]=='+')i++;
        ans=0;
        int vis=0;
        for(j=i;j<len;j++)
        {
            if(str[j]>='0'&&str[j]<='9')
            {
                ans=ans*10+str[j]-'0';
                vis=1;
                if(flag==0&&ans>INT_MAX)return INT_MAX;
                if(flag==1&&-ans<INT_MIN)return INT_MIN;
            }
            else break;
        }
        if(vis==0)return 0;
        else if(flag==0)return (int)ans;
        else if(flag==1)
        {
            if(ans==0)return 0;
            else return (int)(-ans);                //强转成int
        }
    }
};

猜你喜欢

转载自blog.csdn.net/Acmer_Sly/article/details/75213679
今日推荐