Reverse and Add
The "reverse and add" method is simple: choose a number, reverse its digits and add it to the original. If the sum is not a palindrome (which means, it is not the same number from left to right and right to left), repeat this procedure.
For example:
195 Initial number
591
-----
786
687
-----
1473
3741
-----
5214
4125
-----
9339 Resulting palindrome
In this particular case the palindrome 9339 appeared after the 4th addition. This method leads to palindromes in a few step for almost all of the integers. But there are interesting exceptions. 196 is the first number for which no palindrome has been found. It is not proven though, that there is no such a palindrome.
Task :
You must write a program that give the resulting palindrome and the number of iterations (additions) to compute the palindrome.
You might assume that all tests data on this problem:
- will have an answer ,
- will be computable with less than 1000 iterations (additions),
- will yield a palindrome that is not greater than 4,294,967,295.
Input
The first line will have a number N with the number of test cases, the next N lines will have a number P to compute its palindrome.
3
195
265
750
Output
For each of the N tests you will have to write a line with the following data : minimum number of iterations (additions) to get to the palindrome and the resulting palindrome itself separated by one space.
4 9339
5 45254
3 6666
Notes:
1.反轉輸入的數字
void reverse_data(int *num,int size,char rev_data[]){
int m=*num;
char data[size];
/*------reverse------*/
sprintf(data,"%d",m);
strcpy(rev_data,data);
strrev(rev_data);
//printf("[%d]%d,%s,%s\n",__LINE__,size,data,rev_data);
}
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void reverse_data(int *num,int size,char rev_data[]){
int m=*num;
char data[size];
/*------reverse------*/
sprintf(data,"%d",m);
strcpy(rev_data,data);
strrev(rev_data);
//printf("[%d]%d,%s,%s\n",__LINE__,size,data,rev_data);
}
int rev_and_add(int *num){
int m=*num;
int palindrome;
int length=sizeof(m);
char rev_num[length];
/*------reverse------*/
reverse_data(&m,length,rev_num);
/*------add------*/
m+=atoi(rev_num);
length=sizeof(m);
reverse_data(&m,length,rev_num);
/*-----test palindrome, 0 means yes, 1 means no.-----*/
char sum[length];
sprintf(sum,"%d",m);
//printf("[%d]%s,%s\n",__LINE__,sum,rev_num);
(strcmp(sum,rev_num)==0)?palindrome=0:palindrome=1;
//printf("[%d],p=%d\n",__LINE__,palindrome);
*num=m;
return palindrome;
//return 0;
}
int main(void){
int total,count,i=0,input,act;
scanf("%d",&total);
while(i<total){
count=0;
i++;
scanf("%d",&input);
do{
//printf("[%d]count=%d\n",__LINE__,count);
act=rev_and_add(&input);
count++;
}while(act==1);
printf("%d %d\n",count,input);
}
return 0;
}
作者已經移除這則留言。
回覆刪除(strcmp(sum,rev_num)==0)?palindrome=0:palindrome=1; 這似乎寫得不太好。直接 palindrome = strcmp(sum,rev_num)==0; 就可以了。若字串相同則 palindrome 為真,否則為偽。
回覆刪除整體來說,程式碼太冗長,而且 strrev 與 atoi 都不是標準函式庫。建議儘量使用標準函式庫,末依賴特定編譯器。
回覆刪除參考程式碼:http://cpp.sh/9jlk (不含使用者輸入)