Skip to content

Instantly share code, notes, and snippets.

@weihsiu
Created October 18, 2014 04:28
Show Gist options
  • Save weihsiu/53c0e846a23156060272 to your computer and use it in GitHub Desktop.
Save weihsiu/53c0e846a23156060272 to your computer and use it in GitHub Desktop.
Q10018: Reverse and Add
#include <stdio.h>
// recursive function, "a" is the accumulator
int _reverse(int n, int a) {
if (n < 10)
return n + a;
else
return _reverse(n / 10, (a + (n % 10)) * 10);
}
// convenient function to simplify calling _reverse()
int reverse(int n) {
return _reverse(n, 0);
}
// palindrome == 迴文
int palindrome(int n) {
return n == reverse(n);
}
void findPalindrome(int n) {
int i;
for (i = 1; !palindrome(n); i++, n += reverse(n)); // empty "for" body
printf("%d %d\n", i, n);
}
int main() {
int c;
scanf("%d", &c);
for (int i = 0; i < c; i++) {
int n;
scanf("%d", &n);
findPalindrome(n + reverse(n));
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment