Created
March 27, 2024 05:13
-
-
Save rbobillot/a4e938371b6150cd067f3df276ca8b27 to your computer and use it in GitHub Desktop.
A quite functional implementation of the atoi function in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int is_digit(const char c) { | |
return c >= '0' && c <= '9'; | |
} | |
int is_space(const char c) { | |
return c >= 8 && c <= 32; | |
} | |
const char *tr_trimhead(const char *s) { | |
return s && is_space(*s) ? tr_trimhead(s+1) : s; | |
} | |
int tr_pow(const int n, const int e, const int res) { | |
return e < 1 ? res : tr_pow(n, e-1, n*res); | |
} | |
int ft_pow(const int n, const int e) { | |
return tr_pow(n, e, 1); | |
} | |
int tr_count_while(const char *s, const char count, int (*check)(char)) { | |
return !check(*s) ? count : tr_count_while(s+1, count+1, check); | |
} | |
int raise(const char digit, const int exp) { | |
return (digit - '0') * tr_pow(10, exp, 1); | |
} | |
int tr_atoi(const char *n, const int exp, const int res, int (*check)(char)) { | |
return !check(*n) ? res : tr_atoi(n+1, exp-1, res+raise(*n, exp), check); | |
} | |
int ft_atoi(const char *s) { | |
const char *num = tr_trimhead(s); | |
const int sign = num && '-' == *num ? -1 : 1; | |
const char *digits = num && ('-' == *num || '+' == *num) ? ++num : num; | |
const int max_exp = tr_count_while(digits, 0, &is_digit) - 1; | |
return !num ? 0 : sign * tr_atoi(digits, max_exp, 0, &is_digit); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment