题目:
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.
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.
题意:
实现atoi函数将字符串转成整数。
Hint:仔细考虑所有可能的输入用例。
思路:
首先清除掉字符串之前可能出现的空白空间,其次注意数字得符号(正数还是负数),还要注意转换之后的整数是否溢出,还要判断字符串的输入是否是有效输入。
1. 不规则输入,但是有效,”-3924x8fc”,” + 413”;
2. 无效格式,” ++c”, ” ++1”;
3. 溢出数据,”2147483648”;
代码:12ms
class Solution { public: int myAtoi(string str) { int sign = 1, base = 0, i = 0; while(str[i]==' ') i++; //删除之前的空白 if(str[i]=='-' || str[i]=='+'){ //保存下整数的正负号 sign = 1 - 2*(str[i++]=='-'); } while(str[i]>='0' && str[i]<='9'){ if(base > INT_MAX/10 || (base==INT_MAX/10 && str[i]-'0'>7)){ //处理溢出情况 if(sign==1) return INT_MAX; else return INT_MIN; } base = 10*base + (str[i++]-'0'); //合成累加整数 } return base*sign; } };代码:12ms
class Solution { public: int myAtoi(string str) { int num = 0, sign = 1, i = 0; const int n = str.size(); while(str[i]==' ' && i<n) i++; //删除前面的空白 if(str[i]=='+'){ //记录下正数符号 i++; }else if(str[i]=='-'){ sign = -1; i++; } for( ; i<n; i++){ if(str[i]<'0' || str[i]>'9') break; //处理不规则输入与无效输入 if(num>INT_MAX/10 || (num==INT_MAX/10 && (str[i]-'0')>INT_MAX%10)){ //处理转换溢出 return sign == -1 ? INT_MIN : INT_MAX; } num = num*10 + (str[i]-'0'); //累加生成整数 } return num*sign; } };