Skip to content

Instantly share code, notes, and snippets.

@ryukinix
Created March 12, 2019 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryukinix/b61af6dad593bb38e0bfcd0c0b3970ba to your computer and use it in GitHub Desktop.
Save ryukinix/b61af6dad593bb38e0bfcd0c0b3970ba to your computer and use it in GitHub Desktop.
Sum posix argv integers
/*
* Manoel Vilela © 2019
*
* Why this? Just because I was bored
* Date: Tue 12 Mar 2019 12:21:48 AM -03
*/
#include <stdio.h>
#include <stdlib.h>
/*
* Power calculate the base^n operation
* @param base value to calculate exponentation
* @param n the exponent
*/
long power(int base, int n) {
if (n == 0) {
return 1;
}
return base * power(base, n - 1);
}
/*
* Calculate the size of a string
* @param string a \0 terminated string
*/
unsigned int string_len(char *string) {
int i;
if (string == NULL) {
return 0;
}
for (i = 0; string[i] != '\0'; i++);
return i;
}
/*
* Parse char to integer
* @param c a valid digit between 0 and 9.
*/
int char_to_int(char c) {
switch(c) {
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
default:
printf("Invalid digit! ABORT!\n");
exit(1);
}
}
/*
* Parse string to integer
* @param string a \0 termined string
*/
long parse_integer(char *string) {
int i = 0;
char c = 0;
long acc = 0;
int s = string_len(string);
#ifdef DEBUG
printf("=> Start string parsing: '%s'\n", string);
printf("Len: '%s' -> %d\n", string, s);
#endif
if (string == NULL || s == 0) {
printf("Empty string found! ABORT!\n");
exit(1);
}
do {
c = string[i++];
long m = power(10, (s - i));
acc += m * char_to_int(c);
} while (i < s);
#ifdef DEBUG
printf("Parsed: %d\n", acc);
#endif
return acc;
}
int main(int argc, char **argv) {
long acc = 0;
#ifdef DEBUG
printf("ARGC: %d\n", argc);
#endif
while (argc-- > 1) {
acc += parse_integer(argv[argc]);
}
printf("%li\n", acc);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment