leetcode 8. String to Integer (atoi)

来源:互联网 发布:手柄键位设置软件mac 编辑:程序博客网 时间:2024/06/16 18:29

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.

class Solution {public:int myAtoi(string str){if (str.size() == 0)    return 0;while (str[0] == ' ')str = str.substr(1, str.size() - 1);        int k = 0;long long sum = 0;if (int(str[0]) >= 48 && str[0] <= 57)sum = int(str[0]) - 48;else if (int(str[0]) == 43)k = 0;else if (int(str[0]) == 45)k = 1;elsereturn 0;for (int i = 1; i < str.size(); i++){   if (int(str[i]) >= 48 && str[i] <= 57 && sum < 2147483649)sum = sum * 10 + (int(str[i]) - 48);elsebreak;}if (k == 1){sum = -sum;    if (sum < INT_MIN)                return INT_MIN;}else        {            if (sum > INT_MAX)                return INT_MAX;        }return sum;}};