This problem is pretty straight forward except for one thing. The unsigned int restriction. The problem says that the palindrome cannot be greater than 2^32 = 4,294,967,295, but somehow, just using unsigned int does not work. Unsigned int is 32-bit, and when I use this, I get wrong answer. When I tried using unsigned long long int which is equivalent to 64-bit, the code got accepted.

To read or write an unsigned long long int, I used %llu instead of the usual %d in printf() or scanf().

To get the digits of an integer, I get the remainder when the number is divided by 10. Get the remainder when the quotient is divided by 10 again. Repeat and repeat until the quotient equals 0. The series of remainders obtained correspond to the digits of the integer.

Here's an implementation that got accepted:

#include "stdio.h"

int main() {

char line[100];

unsigned long long int num, q, r, l, mid, ispal, rnum, pow, sum;

int i, j, k, num_input, count;

unsigned int array[100];

scanf("%d", &num_input);

for (k = 0; k < num_input; k += 1) {

scanf("%llu", &num);

q = num;

l = 0;

while (q > 0) {

r = q % 10;

q /= 10;

array[l] = r;

l += 1;

}

sum = num;

count = 0;

do {

count += 1;

rnum = 0;

pow = 1;

for (i = l - 1; i >= 0; i -= 1) {

rnum = rnum + (array[i] * pow);

pow = pow * 10;

}

sum = sum + rnum;

// printf("sum=%d\n", sum);

q = sum;

l = 0;

while (q > 0) {

r = q % 10;

q /= 10;

array[l] = r;

l += 1;

}

mid = l / 2;

ispal = 1;

for (i = 0, j = l - 1; i < mid; i += 1, j -= 1) {

if (array[i] != array[j]) {

ispal = 0;

break;

}

}

} while (ispal == 0);

printf("%d %llu\n", count, sum);

}

return 0;

}

## No comments:

## Post a Comment