TOJ 4002 Palindrome Generator

描述

A palindrome is a number that reads the same whether you read it from left to right or from right to left. Here is a surprising fact. Suppose we start with a number n. We reverse the digits of n and add it to n. If this number is a palindrome we stop. Otherwise, we repeat the reversal and addition and continue. For many numbers this process leads us to a palindrome!

In this task you will be given a number n with at most 10 digits. Your task is to carry out the process described above and output the resulting palindrome, if you find one. However, if the number of digits exceeds 30 and you still have not found a palindrome then output -1.

For example if n is 149 then we get the following sequence: 149, 1090, 1991. Thus your program should output 1991 in this case. However, if we start with 196 we do not get a palindrome before the number of digits exceeds 30 and in this case the output should be -1.

输入

A single line with a single integer n, with not more than 10 digits.

You may assume that n has at most 10 digits.

输出

A single number that is either -1 or the palindrome generated by the process described above.

样例输入

149

样例输出

1991

题目来源

TOJ

题目意思很简单,输出回文数。如果不是回文那么就把它反一反相加。继续判断,如果超过30位还不是回文就将它输出来。

注意是大数,所以使用数组存储。

#include <stdio.h>

__int64 n;
int maxDigit;
int num[100];
int renum[100];
int out[100];

bool palindrome(){
    int k=maxDigit-1;
    for(int i=0;i<maxDigit/2; i++,k--){
        if(out[i]!=out[k])return 0;
    }
    return 1;
}

void getNum(){
    int k=0;
    for(int i=0; i<maxDigit; i++){
        num[k++]=out[i];
    }    
}

void getRenum(){
    int k=0;
    for(int i=maxDigit-1; i>=0; i--){
        renum[k++]=num[i];
    }
}

void plus(){
    int carry=0;
    int cnt=0;
    int digit=0;
    for(int i=maxDigit-1; i>=0 || carry!=0; i--){
        if(i>=0){
            out[cnt++]=(num[i]+renum[i]+carry)%10;
            carry=(num[i]+renum[i]+carry)/10;
            digit++;        
        }else{
            out[cnt++]=carry%10;
            carry=carry/10;
            digit++;
        }
    }
    maxDigit=digit;
}

bool judge(){
    int flag=1;
    //如果这个数不是回文 
    while(!palindrome()){
        getNum();
        getRenum();
        plus();
        if(maxDigit>30){
            flag=0;
            break;
        }
    }
    return flag;
}

int main(int argc, char *argv[])
{
    while( scanf("%I64d",&n)!=EOF ){
        int cnt=0;
        maxDigit=0;
        while(n!=0){
            out[cnt++]=n%10;
            n/=10;
            maxDigit++;
        }
        if(!judge()){
            printf("-1
");
        }else{
            for(int i=maxDigit-1; i>=0; i--){
                printf("%d",out[i]);
            }
            printf("
");
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/chenjianxiang/p/3549801.html