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.
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 returned.
解题思路:注意前置空格的处理/溢出的处理以及正负号的处理.15ms AC class Solution { public: int myAtoi(string str) { int len = str.length(); int it = 0; int flag = 2;//0表示正数,1表示负数 if(len == 0)//字符串为空 { return 0; } while(str[it] == ' ') { it++; } if(it == len)//全是空格 { return 0; } if(str[it] == '+') { flag = 0; it++; } else if(str[it] == '-') { flag = 1; it++; } else if(!(str[it]>='0'&&str[it]<='9'))//首字母是非数字 { return 0; } string tmp = ""; while(str[it]>='0' && str[it]<='9') { tmp += str[it++]; } len = tmp.length();//实际要转换的字符串 long long res = 0; if(flag == 1) { if(tmp == "2147483648") { return INT_MIN; } } int of = 0; for(int i=len-1;i>=0;i--) { res += (tmp[i]-'0')*pow(10.0,len-i-1); if(res > INT_MAX) { of = 1; break; } } if(of == 1)//overflow { if(flag != 1) return INT_MAX; else return INT_MIN; //return INT_MAX*pow((-1),flag); } else { return res*pow((-1),flag); } return res; } };然后再附上网友的简短代码
int myAtoi(string str) { long result = 0; int indicator = 1; for(int i = 0; i<str.size();) { i = str.find_first_not_of(' '); if(str[i] == '-' || str[i] == '+') indicator = (str[i++] == '-')? -1 : 1; while('0'<= str[i] && str[i] <= '9') { result = result*10 + (str[i++]-'0'); if(result*indicator >= INT_MAX) return INT_MAX; if(result*indicator <= INT_MIN) return INT_MIN; } return result*indicator; } }