How to create recursive implementation of atoi() for positive and negative numbers in C

1 Answer

0 votes
#include <stdio.h>

long _atoi(const char *str) {
    long num = 0;
    int i = 0, sign = 1;

    if (str[i] == '+' || str[i] == '-') {
        if (str[i] == '-') {
            sign = -1;
        }
        i++;
    }
 
    while (str[i] && (str[i] >= '0' && str[i] <= '9')) {
        num = num * 10 + (str[i] - '0');
        i++;
    }
 
    return sign * num;
}
  
int main()
{
    char str[] = "-96291807235";
     
    long n = _atoi(str);
     
    printf("%ld", n);
     
    return 0;
}
 
 
 
 
/*
run:
      
-96291807235
 
*/

 



answered Nov 24, 2023 by avibootz

Related questions

1 answer 125 views
1 answer 127 views
127 views asked Nov 24, 2023 by avibootz
1 answer 342 views
1 answer 120 views
1 answer 149 views
1 answer 123 views
...