#include "my_atoi.h" int my_atoi(const char *str) { int res = 0; // str error check if (str == NULL || *str == '0') { return 0; } // trim whitespaces for (; *str && *str == ' '; str++) { continue; } // move to end of str size_t l; for (l = 0; str[l]; l++) { continue; } l--; // prepare for calculations int factor = 1; // actual conversion of up to the second element of str (potential sign) for (; l > 0; l--) { char val = str[l]; if (val < '0' || val > '9') { return 0; } val -= '0'; res += val * factor; factor *= 10; } // l should be 0 by now if (str[l] == '-') { return -res; } else if (str[l] != '+') { int val = str[l]; if (val < '0' || val > '9') { return 0; } val -= '0'; return res + val * factor; } return res; }