leetcode 8

string类型转换为int类型,需要考虑不同的转换情况。

“   04”  转换结果   4;

“   4   43”  转换结果  4;

“a@12 ”   转换结果    0;

“12a”    转换结果    12;

“ +12”   转换结果    12;

“ +  12”  转换结果   0;

“ -12”   转换结果     -12;

“  -  12”  转换结果    0;

“ +-12”   转换结果   0;

 

其次就是对边界的考虑,若转换之后的数越上界,则返回上界;若转换之后的数越下界,则返回下界。

 

代码如下:

class Solution {
public:
    int myAtoi(string str) {
        int result = 0;
        bool sign = true;
        int tag = 0;
        for(int i = 0; i < str.length(); ++i)
        {
            if(str[i] ==  ' ' && tag == 0)
            {
                continue;
            }
            if(str[i] == '+' && tag == 0)
            {
                tag = 1;
                continue;
            }
            if(str[i] == '-' && tag == 0)
            {
                tag = 1;
                sign = false;
                continue;
            }
            while(i < str.length())
            {
                if((str[i] - '0') < 0 || (str[i] - '9') > 9)
                {
                    return sign? result : -result; 
                }
                if(result > INT_MAX / 10)
                {
                    return  sign? INT_MAX : INT_MIN;
                }
                result *= 10;
                if ((str[i] - '0') > (INT_MAX - result))  
                    return sign? INT_MAX : INT_MIN;
                result = result + str[i] - '0';
                i ++;
            }
        }
        return sign? result : -result;
    }
};

 

posted @ 2016-09-01 15:13  花椰菜菜菜菜  阅读(232)  评论(0编辑  收藏  举报