fork(1) download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. string trimLeft(string str) {
  5. if (!str.size()) return "";
  6. int i = 0;
  7. while (str[i] == ' ' || str[i] == '0') {
  8. i++;
  9. }
  10.  
  11. return str.substr(i);
  12. }
  13.  
  14.  
  15. int getFirstInvalidIndex(string str) {
  16. if (!str.size()) return 0;
  17. int index = 0;
  18.  
  19. while (isdigit(str[index])) {
  20. index++;
  21. }
  22.  
  23. return index;
  24. }
  25.  
  26. int myAtoi (string str) {
  27. if (!str.size()) return 0;
  28.  
  29. str = trimLeft(str);
  30.  
  31. bool hasNegativeSymbol = str[0] == '-';
  32. bool hasPositiveSymbol = str[0] == '+';
  33. string s = (hasNegativeSymbol || hasPositiveSymbol) ? str.substr(1) : str;
  34.  
  35.  
  36. int firstInvalidIndex = getFirstInvalidIndex(s);
  37. if (firstInvalidIndex == s.size() && !isdigit(s[s.size() - 1])) return 0;
  38.  
  39. s = s.substr(0, firstInvalidIndex);
  40.  
  41. int size = s.size(), result = 0, currentPower = 0;
  42.  
  43. for (int i = size - 1; i >= 0; i--) {
  44. int currentNumber = s[i] - '0';
  45. result = result + (currentNumber * pow(10, currentPower++));
  46. }
  47.  
  48. return hasNegativeSymbol ? -result : result;
  49. }
  50.  
  51. int main() {
  52. string s;
  53.  
  54. while (cin >> s) {
  55. cout << myAtoi(s) << endl;
  56. }
  57.  
  58. return 0;
  59. }
Success #stdin #stdout 0.01s 5280KB
stdin
45434
    -0042
000042400000
1337dl565
0490-34-0
   -00042
stdout
45434
-42
42400000
1337
490
-42