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. bool hasNegativeSymbol = str[0] == '-';
  30. bool hasPositiveSymbol = str[0] == '+';
  31. string s = (hasNegativeSymbol || hasPositiveSymbol) ? str.substr(1) : str;
  32.  
  33. s = trimLeft(s);
  34.  
  35. int firstInvalidIndex = getFirstInvalidIndex(s);
  36. if (firstInvalidIndex == s.size() && !isdigit(s[s.size() - 1])) return 0;
  37.  
  38. s = s.substr(0, firstInvalidIndex);
  39.  
  40. int size = s.size(), result = 0, currentPower = 0;
  41.  
  42. for (int i = size - 1; i >= 0; i--) {
  43. int currentNumber = s[i] - '0';
  44. result = result + (currentNumber * pow(10, currentPower++));
  45. }
  46.  
  47. return hasNegativeSymbol ? -result : result;
  48. }
  49.  
  50. int main() {
  51. string s;
  52.  
  53. while (cin >> s) {
  54. cout << myAtoi(s) << endl;
  55. }
  56.  
  57. return 0;
  58. }
Success #stdin #stdout 0s 5284KB
stdin
45434
    -0042
000042400000
1337dl565
0490-34-0
stdout
45434
-42
42400000
1337
490