[LeetCode 解题报告]008.String to Integer (atoi)

来源:互联网 发布:node.js高级编程 微盘 编辑:程序博客网 时间:2024/05/29 08:22

Description:

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.

spoilers alert... click to show requirements for atoi.

注意Case点:

  • 该字符串前边可能有若干空格(用#表示空格)“###010”返回值应为10
  • 去除前边的若干个空格之后,需考虑接下来的一个字符是‘+‘还是’-’
  • 碰到非数字字符结束
  • 转换成数字时候需考虑是否产生越界

class Solution {public:    int myAtoi(string str) {                if(str.length() == 0)            return 0;                int i = 0, sign = 1, res = 0;        while(isspace(str[i]))            i ++;                if(str[i] == '+' || str[i] == '-') {            if(str[i] == '-')                sign = 0;            i ++;        }                str = str.substr(i);                for(int j = 0; j < str.length(); j ++) {            if(!isdigit(str[j])) {                str = str.substr(0, j);                break;            }        }                if(str.length() == 0)            return 0;        for(int i = 0; i < str.length(); i ++) {                        int c = (str[i] - '0');                        if(sign == 1 && (res > INT_MAX / 10 || res == INT_MAX / 10 && c > INT_MAX % 10))            {                return INT_MAX;            }            else if(sign == 0 && (res > INT_MAX / 10) || res == INT_MAX / 10 && c > (INT_MAX % 10 + 1))            {                return INT_MIN;            }            res = res * 10 + c;                    }        return sign > 0 ? res : -res;    }};


原创粉丝点击