Created
June 30, 2016 19:09
-
-
Save souenzzo/0ddd322ee44824a5ca6aa814b4225367 to your computer and use it in GitHub Desktop.
Desavio, com tail rec
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
#include <stdio.h> | |
// base ^ power | |
int fpow(int base, int power) { | |
return (power == 1) ? 1 : base * fpow(base, power - 1); | |
} | |
// Ultimo digito do numero | |
int last(int num, int base) { | |
return num % base; | |
} | |
// Todos, menos ultimo digito do numero | |
int init(int num, int base) { | |
return num / base; | |
} | |
// Numero de digitos do numero | |
int len(int num, int base) { | |
return (num == 0) ? 0 : 1 + len(init(num, base), base); | |
} | |
// Primeiro digito do numero | |
int head(int num, int base) { | |
return num / fpow(base, len(num, base)); | |
} | |
// Todos, menos primeiro digito do numero | |
int tail(int num, int base) { | |
return num % fpow(base, len(num, base)); | |
} | |
// Inverte a ordem dos digitos do numero | |
int rev(int num, int base) { | |
return (num == 0) ? 0 : head(num, base) + (base * rev(tail(num, base), base)); | |
} | |
// Formata a função de acordo com o desafio (int -> int) | |
int desafio(int i) { | |
return rev(i, 10); | |
} | |
int main (int argc, char **argv) { | |
if (argc != 2) { | |
return 1; | |
} | |
int n; | |
sscanf(argv[1], "%d", &n); | |
printf("%d\n", desafio(n)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment