UVa10018 - Reverse and Add

#include <stdio.h>
#include <string.h>

#define MAX 20

int is_palindrome(char *str);
void reverse(char *from, char *to);

int main()
{
    int n;
    unsigned int a, b, sum;
    int count;
    char buf[MAX], temp[MAX];

    setvbuf(stdout, NULL, _IONBF, 0);

    scanf("%d", &n);

    while (n--) {
        scanf("%s", buf);
        count = 0;

        while (!is_palindrome(buf)) {
            count++;
            sscanf(buf, "%u", &a);
            reverse(buf, temp);
            strcpy(buf, temp);
            sscanf(buf, "%u", &b);
            sum = a + b;
            sprintf(buf, "%u", sum);
        }
        printf("%d %s\n", count, buf);

    }
    return 0;
}

int is_palindrome(char *str)
{
    int i;
    int len = strlen(str);

    for (i = 0; i < len / 2; i++) {
        if (str[i] != str[len - 1 - i])
            return 0;
    }

    return 1;
}

void reverse(char *from, char *to)
{
    int i, len = strlen(from);

    for (i = 0; i < len; i++)
        to[i] = from[len - 1 - i];
    to[len] = '\0';
}

你可能感兴趣的:(UVa10018 - Reverse and Add)