|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + int myAtoi(string str) { |
| 4 | + int answer=0; |
| 5 | + int i=0; |
| 6 | + string s(str); |
| 7 | + int l = s.length(); |
| 8 | + bool sign = true; |
| 9 | + while(i<l && s[i] == ' ') |
| 10 | + i++; |
| 11 | + cout<<"\nall the leading whitespaces trimmed"; |
| 12 | + if((s[i]<'0' || s[i]>'9') && s[i] != '-' && s[i] !='+') |
| 13 | + return 0; |
| 14 | + cout<<"\nstarting the processing"; |
| 15 | + if(s[i] == '-') { |
| 16 | + sign = false; |
| 17 | + i++; |
| 18 | + cout<<"\nNumber is negative"; |
| 19 | + } else if (s[i] == '+') { |
| 20 | + i++; |
| 21 | + } |
| 22 | + |
| 23 | + while(i<l) { |
| 24 | + cout<<"\nhere is the element s["<<i<<"] \t"<<s[i]; |
| 25 | + if(s[i]==' ') { |
| 26 | + break; |
| 27 | + } |
| 28 | + if(s[i] >= '0' && s[i] <='9') { |
| 29 | + int x = s[i]-'0'; |
| 30 | + //cout<<"\n x="<<x; |
| 31 | + if(sign && static_cast<long int>(answer)*10 + x >= INT_MAX) { |
| 32 | + return INT_MAX; |
| 33 | + } else if (!sign && static_cast<long int>(answer)*10 + x > INT_MAX) { |
| 34 | + return INT_MIN; |
| 35 | + } |
| 36 | + answer = answer*10 + x; |
| 37 | + i++; |
| 38 | + } else { |
| 39 | + return (sign ? answer : -answer); |
| 40 | + } |
| 41 | + cout<<"\nanswer= "<<answer; |
| 42 | + } |
| 43 | + return (sign ? answer : -answer); |
| 44 | + |
| 45 | + } |
| 46 | +}; |
| 47 | + |
| 48 | +string stringToString(string input) { |
| 49 | + assert(input.length() >= 2); |
| 50 | + string result; |
| 51 | + for (int i = 1; i < input.length() -1; i++) { |
| 52 | + char currentChar = input[i]; |
| 53 | + if (input[i] == '\\') { |
| 54 | + char nextChar = input[i+1]; |
| 55 | + switch (nextChar) { |
| 56 | + case '\"': result.push_back('\"'); break; |
| 57 | + case '/' : result.push_back('/'); break; |
| 58 | + case '\\': result.push_back('\\'); break; |
| 59 | + case 'b' : result.push_back('\b'); break; |
| 60 | + case 'f' : result.push_back('\f'); break; |
| 61 | + case 'r' : result.push_back('\r'); break; |
| 62 | + case 'n' : result.push_back('\n'); break; |
| 63 | + case 't' : result.push_back('\t'); break; |
| 64 | + default: break; |
| 65 | + } |
| 66 | + i++; |
| 67 | + } else { |
| 68 | + result.push_back(currentChar); |
| 69 | + } |
| 70 | + } |
| 71 | + return result; |
| 72 | +} |
| 73 | + |
| 74 | +int main() { |
| 75 | + string line; |
| 76 | + while (getline(cin, line)) { |
| 77 | + string str = stringToString(line); |
| 78 | + |
| 79 | + int ret = Solution().myAtoi(str); |
| 80 | + |
| 81 | + string out = to_string(ret); |
| 82 | + cout << out << endl; |
| 83 | + } |
| 84 | + return 0; |
| 85 | +} |
0 commit comments