8. String to Integer (atoi) (重要)

来源:互联网 发布:网络通信运营商 编辑:程序博客网 时间:2024/05/16 19:44

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.

注意5点。

1.空字符串

2.字符串前的空格

3.+-号

4.非法字符(这里返回非法字符前的有效位)

5.溢出(这里如果大于最大,返回最大;小于最小返回最小)


class Solution {public:int myAtoi(string str) {int len = str.size();if (len == 0) return 0;long long sum = 0;int i = 0;while (str[i] == ' ') i++;int minus = 1;if (str[i] == '-'){minus = -1;i++;}else if (str[i] == '+'){i++;}for (; i < len; i++){if (str[i]<'0' || str[i]>'9'){break;}sum = sum*10 + (str[i] - '0')*minus;if (sum>INT_MAX){return INT_MAX;}else if (sum < INT_MIN){return INT_MIN;}}return sum;}};


0 0
原创粉丝点击