8. String to Integer (atoi)Total Accepted:
91403 all submissions:
683692 Difficulty:
Easy
Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please don't see below and ask yourself what is the possible input cases.
Notes: It is intended for the problem to be specified vaguely (ie, no given input specs). You is 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 on 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, the starting from this character, takes a optional initial plus or minus sign followed by as many numerical digits as P Ossible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which is ignored and has no Effe CT on the behavior of this function.
If the first sequence of non-whitespace characters in STR isn't a valid integral number, or if no such sequence exists be Cause 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 Returne D.
Similar to the previous question, the same definition of the res as long is used to avoid overflow, first calculate the value of res and then determine whether overflow.
classSolution { Public: intMyatoi (stringstr) { if(str.length () = =0) return 0; inti =0; while(Str[i] = =' ') I++; if(i = =str.length ())return 0; Long Longres=0; intIsPo =1; if(Str[i] = ='-') {IsPo= -1; I++; } Else if(Str[i] = ='+') {IsPo=1; I++; } for(i; I < str.length (); i++) { if(str[i]<'0'|| Str[i]>'9') Break; Res= Res *Ten+ str[i]-'0'; } Res= res*IsPo; if(res>Int_max)returnInt_max; Else if(Res <int_min)returnint_min; returnRes; }};
But in the previous question, the number that was used for the transformation is the int type, the number of digits is fixed, and the value after flipping does not exceed the range of long type. The string in this topic may be infinitely long, so a long type can still overflow. So we're going to make a decision about whether to overflow each time we add a single number to res.
for(i; I < str.length (); i++) { if(str[i]<'0'|| Str[i]>'9') Break; Res= Res *Ten+ Str[i]-'0'; if(ispo*res>Int_max)returnInt_max; Else if(Ispo*res <int_min)returnint_min; }
Leetcode:string to Integer (atoi)