Although the topic is easy, but I submitted 10 times before, even hard bar.
Mostly I didn't think about it in many cases. And sometimes my rules are different from the ones in the answers.
The rules of the answer:
1. Leading spaces skip All "123" = 123
2. The sign should consider "+123" = 123 "123" = 123
3. Leading 0 of the number to skip "0000123" = "123"
4. A non-numeric value is encountered in the digital phase, and the number is truncated " -0000 123" = 0 "123a213" = 123
5. No valid number, return 0 "+-123" = 0
6. Number out of bounds, return maximum value 2147483647 or minimum-2147483648
Idea: First use strcpy to get a valid number part (first skip leading space, get sign, up to non-digit part)
Then judge the strcpy length as 0 or only one-+ +, returning 0. (No valid numbers)
There is a valid number that converts the obtained number to a string, and the strcmp determines whether it is the same. Different indicates a digital overflow.
If the input number is positive, the maximum value is returned, and the minimum value is returned instead.
#include <iostream>#include<vector>#include<algorithm>#include<queue>#include<stack>#include<string.h>using namespacestd;classSolution { Public: intAtoiConst Char*str) { Charscheck[ -];//Determine if overflow Charstrcpy[ -];//a valid number part of the input string intAns =0; inti =0; inticpy =0; //Remove leading spaces while(Str[i] = =' ') {i++; } if(Str[i] = ='+'|| Str[i] = ='-') {strcpy[icpy+ +] = str[i++]; } //Remove the leading 0 that follows the sign while(Str[i] = ='0') {i++; } for(; Str[i]! =' /'; i++) { if('0'<= Str[i] && Str[i] <='9') {ans= ans *Ten+ (Str[i]-'0'); strcpy[icpy++] =Str[i]; } Else { Break; }} strcpy[icpy]=' /'; if(strlen (strcpy) = =0) { return 0; } Else if(strlen (strcpy) = =1&& (strcpy[0] =='+'|| strcpy[0] =='-')) { return 0; } if(strcpy[0] =='-') {ans=0-ans; sprintf (Scheck,"%d", ans); } Else if(strcpy[0] =='+') {scheck[0] ='+'; sprintf (Scheck+1,"%d", ans); } Else{sprintf (Scheck,"%d", ans); } if(strcmp (Scheck, strcpy)! =0) { if(strcpy[0] =='-') {ans= -2147483648; } Else{ans=2147483647; } } returnans; }};intMain () {solution S; Charstr[ -] ="2147483648"; intAns =s.atoi (str); return 0;}
"Leetcode" atoi (Hard) ★