zcmu 1119
1119: 反转然后相加
Description
假设你有一个整数a,将它各位数字反转以后得到b,然后a=a+b,直到a是回文数为止.求出几次反转相加后能得到一个回文数,输出最小的次数和回文数.例如:
195 初始的a
591
-----
786
687
-----
1473
3741
-----
5214
4125
-----
9339 最终结果
Input
多组测试数据。
每组测试数据包含1个正整数a。(a<=10000)
Output
对于每组测试数据,输出产生回文数的最小次数和这个回文数.
如果超过20次运算还没出现回文数则输出”impossible”.
Sample Input
195
265
750
Sample Output
4 9339
5 45254
3 6666
解题思路:写一个判断回文的函数,和一个反转的函数即可。注意大于20次输出imposs。
代码如下:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<time.h>
using namespace std;
#define FORA(i,x,y) for(int i = x; i < y; i++)
#define FORB(i,x,y) for(int i = x; i <= y; i++)
#define FORC(i,y,x) for(int i = y; i > x; i--)
#define FORD(i,y,x) for(int i = y; i >= x; i--)
#define INF 1000000000
#define LL long long
const int mod = 1000000;
const int maxn = 1000000;
long long a[maxn];
int isPalindrom(long long n){
if(n < 10) return 1;
int k = 0;
while(n){
a[k++] = n % 10;
n /= 10;
}
int t = k - 1;
FORA(i,0,k/2){
if(a[i] != a[t--]){
return 0;
break;
}
}
return 1;
}
long long reversal(long long n){
long long sum = 0;
int k = 0;
while(n){
a[k++] = n % 10;
n /= 10;
}
long long t = k - 1;
long long p = 1;
FORA(i,0,k){
FORB(j,1,t){
p *= 10;
}
sum += a[i] * p;
p = 1;
t--;
}
return sum;
}
int main(){
long long x;
while(cin >> x){
int c = 1;
if(isPalindrom(x)) printf("0 %lld\n",x);
else{
long long b = reversal(x);
while(c <= 20){
x += b;
if(isPalindrom(x)){
printf("%d %lld\n",c,x);
break;
}
else b = reversal(x);
c++;
}
if(c > 20) printf("impossible\n");
}
}
return 0;
}
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<time.h>
using namespace std;
#define FORA(i,x,y) for(int i = x; i < y; i++)
#define FORB(i,x,y) for(int i = x; i <= y; i++)
#define FORC(i,y,x) for(int i = y; i > x; i--)
#define FORD(i,y,x) for(int i = y; i >= x; i--)
#define INF 1000000000
#define LL long long
const int mod = 1000000;
const int maxn = 1000000;
long long a[maxn];
int isPalindrom(long long n){
if(n < 10) return 1;
int k = 0;
while(n){
a[k++] = n % 10;
n /= 10;
}
int t = k - 1;
FORA(i,0,k/2){
if(a[i] != a[t--]){
return 0;
break;
}
}
return 1;
}
long long reversal(long long n){
long long sum = 0;
int k = 0;
while(n){
a[k++] = n % 10;
n /= 10;
}
long long t = k - 1;
long long p = 1;
FORA(i,0,k){
FORB(j,1,t){
p *= 10;
}
sum += a[i] * p;
p = 1;
t--;
}
return sum;
}
int main(){
long long x;
while(cin >> x){
int c = 1;
if(isPalindrom(x)) printf("0 %lld\n",x);
else{
long long b = reversal(x);
while(c <= 20){
x += b;
if(isPalindrom(x)){
printf("%d %lld\n",c,x);
break;
}
else b = reversal(x);
c++;
}
if(c > 20) printf("impossible\n");
}
}
return 0;
}