Skip to content

Instantly share code, notes, and snippets.

@souenzzo souenzzo/rev_rec.c
Created Jun 30, 2016

Embed
What would you like to do?
Desavio, com tail rec
#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
You can’t perform that action at this time.