PC 110502 Reverse and Add //水题 字符串 模拟

来源:互联网 发布:airplayer for mac 编辑:程序博客网 时间:2024/04/28 23:01




The reverse and add function starts with a number,reverses its digitsand adds the reverse to the original.If the sum is not a palindrome (meaningit does not give the same number read from left to right and right to left),we repeatthis procedure until it does.

For example, if we start with 195 as the initial number, we get 9,339as the resulting palindrome after the fourth addition:

195 786 1,473 5,214591 687 3,741 4,125+ --- + --- + --- + ---786 1,473 5,214 9,339

This method leads to palindromes in a few steps for almost all of the integers.But there are interesting exceptions. 196 is the first number for whichno palindrome has been found.It has never been proven, however, that nosuch palindrome exists.

You must write a program that takes a given number and givesthe resulting palindrome (if one exists) and thenumber of iterations/additions it took to find it.

You may assume that all the numbers used as test data will terminate inan answer with less than 1,000 iterations (additions),and yield a palindrome that is not greater than 4,294,967,295.

Input

The first line will contain an integer N (0 <N<=100), giving the number oftest cases, while the nextN lines each contain a single integer P whose palindromeyou are to compute.

Output

For each of the N integers, print a line giving the minimum number of iterations to find the palindrome, a single space,and then the resulting palindrome itself.

Sample Input

3195265750

Sample Output

4 93395 452543 6666

这道题不难,思路也非常清晰,但是实践起来有点别扭。
没什么可注意的。。一次AC

#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <cstdlib>using namespace std;void add (char *str1, char *str2, char *str3){int i, j, i1, i2, tmp, carry;int len1 = strlen(str1), len2 = strlen(str2);char ch;i1 = len1- 1; i2 = len2 - 1;j = carry = 0;for (; i1>= 0 && i2 >= 0; ++j, --i1, --i2){tmp = str1[i1] -'0' + str2[i2] - '0' + carry;carry = tmp / 10 ; str3[j] = tmp % 10 + '0';}while (i1 >= 0){tmp = str1[i1--] -'0' + carry;carry = tmp / 10;str3[j++] = tmp % 10 +'0';}while (i2 >= 0){tmp = str2[i2--] -'0' + carry;carry = tmp / 10;str3[j++] = tmp % 10 +'0';}if (carry) str3[j++] = carry + '0';str3[j] = '\0';for (i =0, --j; i<j; ++i, --j){ch = str3[i]; str3[i] = str3[j]; str3[j] = ch;}}bool judge (char *str1, int len){int i;for (i = 0; i <len /2 ; i++){if (str1[i]!=str1[len -1 -i]) return false;}return true;}void rev( const char *str1, char *str2 , int len){int i, j = 0;for (i = len-1; i>=0 ; i--){str2[j] = str1[i];++j; }str2[j] = '\0';}int main(){char s1[20], s2[20], s3[20], s4[20];int i, j ,countn, len1, len2;int cases;cin>>cases;while (cases--){countn = 0;cin>>s1;len1 = strlen(s1);rev(s1, s2, len1);add(s1,s2,s3);len1 = strlen(s3);while ( !judge (s3, len1)){strcpy(s1,s3);len1 = strlen(s1);rev(s1, s2, len1);add(s1,s2,s3);len1 = strlen(s3);++countn;}cout<<countn+1 <<" "<<s3<<endl;}return 0;}