From a94711362f844d5de6b498d05f12611312e22e0d Mon Sep 17 00:00:00 2001 From: zachir Date: Wed, 6 Mar 2024 23:31:51 -0600 Subject: Use strtol instead of checking each digit This makes it both faster and smaller. --- main.c | 34 ++++++++++++++++------------------ main.h | 1 + 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/main.c b/main.c index c1a8b23..d986924 100644 --- a/main.c +++ b/main.c @@ -29,12 +29,13 @@ void printversion() { int main(int argc, char **argv) { bool quiet; - size_t string_length; - uint8_t digit; + bool value; + long result; - digit = 0; quiet = false; - string_length = 0; + value = false; + result = 0; + char *output; if (argc > 1) { for (size_t i = 1; i < argc; i++) { @@ -52,26 +53,23 @@ int main(int argc, char **argv) { case 'q': quiet = true; break; - default: - printhelp(); - return -1; } } + result = strtol(argv[i], &output, 10); + value = true; } - assert(strlen(argv[argc - 1]) < SIZE_MAX); - string_length = strlen(argv[argc - 1]); - digit = argv[argc - 1][string_length - 1]; - digit -= '0'; - if (quiet) { - if (digit <= 10) - return ((digit & 1) == 0) ? SUCCESS : ERR; - } else { - if ((digit & 1) == 0) { + } + if (value) { + if (result % 2 == 0) { + if (quiet) { fprintf(stdout, "even\n"); - } else { + } + return 0; + } else { + if (quiet) { fprintf(stdout, "odd\n"); } - return SUCCESS; + return 1; } } return ERR; diff --git a/main.h b/main.h index 61f7b1c..d6d758e 100644 --- a/main.h +++ b/main.h @@ -6,6 +6,7 @@ #include #include #include +#include #include #include -- cgit v1.2.3