题解 UVA10018 【Reverse and Add】

· · 题解

题目

这是一道模拟题

首先,对于一个数字,我们每对它进行一步操作后都要判断是否为回文数,所以我们需要一个判断回文数的函数。

那么,怎么写呢?

我的方法是把整数化为字符串,从字符串两端向中间判断,如下:

bool huiwen(long long n){
    char c[50];
    int z=0;
    memset(c,0,sizeof(c));
    while(n>0){
        c[z++]=n%10;
        n=n/10;
    }
    for(int i=0;i<z/2;i++){
        if(c[i]!=c[z-i-1]){
            return false;
        }
    }
    return true;
}

接下来就是模拟过程了,注意答案可能会爆 \mathrm{int} 哦 !

Code:

#include<bits/stdc++.h>
using namespace std;

typedef long long ll;

bool huiwen(ll n){
    char c[50];
    int z=0;
    memset(c,0,sizeof(c));
    while(n>0){
        c[z++]=n%10;
        n=n/10;
    }
    for(int i=0;i<z/2;i++){
        if(c[i]!=c[z-i-1]){
            return false;
        }
    }
    return true;
}

void bian(ll n){
    ll ans=0;
    while(!huiwen(n)){//直到n是回文数为止
        ll t=0;//t存储翻转后的n
        ll z=n;
        while(n>0){
            ll temp=n%10;
            t=t*10+temp;
            n=n/10;
        }
        n=t+z;
        ans++;
    }
    printf("%lld %lld\n",ans,n);
}

int main(){
    ll n,t;
    scanf("%lld",&n); 
    for(ll i=0;i<n;i++){
        scanf("%lld",&t);
        bian(t);
    }
    return 0;
}