mplement 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.
1 class Solution { 2 public: 3 int myAtoi(string str) { 4 long long res=0; 5 int n=str.size(); 6 if(n<1) return 0; 7 int i=0; 8 int flag=0; 9 int flagnum=0; 10 for(i=0;i<n;i++) 11 { 12 if(str[i]==' '&&!flag&&!flagnum) continue; 13 if(flag==0) 14 { 15 if(str[i]=='-') 16 { 17 flag=2; 18 continue; 19 } 20 else if(str[i]=='+') 21 { 22 flag=1; 23 continue; 24 } 25 } 26 if(str[i]>='0'&&str[i]<='9') 27 { 28 flagnum++; 29 res=res*10+(str[i]-'0'); 30 } 31 else break; 32 if(res>INT_MAX||(flag==2&&res>2147483648)) 33 break; 34 } 35 if(res>INT_MAX||(flag==2&&res>2147483648)) 36 { 37 res=(flag==2)?INT_MIN:INT_MAX; 38 } 39 else 40 res=(flag==2)?-res:res; 41 return res; 42 } 43 };
class Solution { public: int atoi(const char *str) { int symbol = 1; int i = 0; if (str == NULL) return 0; int n = strlen(str); while(str[i]==' '||str[i]=='0') i++; if(str[i]=='+' || str[i]=='-') { symbol = str[i]=='+' ? 1:-1; i++; } long res =0; for(;i<n;++i) { int k=str[i]-'0'; if(k>=0&&k<=9) { res=res*10+k; } else break; } res *=symbol; if(res>INT_MAX) return INT_MAX; if(res<INT_MIN) return INT_MIN; return (int)res; } };