PAT_A1024#Palindromic Number

Source:

PAT A1024 Palindromic Number (25 分)

Description:

A number that will be the same when it is written forwards or backwards is known as a Palindromic Number. For example, 1234321 is a palindromic number. All single digit numbers are palindromic numbers.

Non-palindromic numbers can be paired with palindromic ones via a series of operations. First, the non-palindromic number is reversed and the result is added to the original number. If the result is not a palindromic number, this is repeated until it gives a palindromic number. For example, if we start from 67, we can obtain a palindromic number in 2 steps: 67 + 76 = 143, and 143 + 341 = 484.

Given any positive integer N, you are supposed to find its paired palindromic number and the number of steps taken to find it.

Input Specification:

Each input file contains one test case. Each case consists of two positive numbers N and K, where N(≤) is the initial numer and K (≤) is the maximum number of steps. The numbers are separated by a space.

Output Specification:

For each test case, output two numbers, one in each line. The first number is the paired palindromic number of N, and the second number is the number of steps taken to find the palindromic number. If the palindromic number is not found after K steps, just output the number obtained at the Kth step and K instead.

Sample Input 1:

67 3

Sample Output 1:

484
2

Sample Input 2:

69 3

Sample Output 2:

1353
3

Keys:

Code:

 1 /*
 2 Data: 2019-07-11 20:22:26
 3 Problem: PAT_A1024#Palindromic Number
 4 AC: 30:25
 5 
 6 题目大意:
 7 非回文数可以通过若干次逆置,相加的方法得到一个回文数;
 8 现给一个数N和步数K,判断K步之内能否得到一个回文数
 9 */
10 #include<cstdio>
11 #include<string>
12 #include<iostream>
13 #include<algorithm>
14 using namespace std;
15 
16 string Add(string s1, string s2)
17 {
18     string s;
19     int carry=0,len=s1.size();
20     for(int i=0; i<len; i++)
21     {
22         int temp = (s1[len-i-1]-'0')+(s2[len-i-1]-'0')+carry;
23         s.insert(s.end(), (temp%10)+'0');
24         carry = temp/10;
25     }
26     if(carry != 0)
27         s.insert(s.end(), carry+'0');
28     reverse(s.begin(),s.end());
29     return s;
30 }
31 
32 bool IsPalin(string s)
33 {
34     for(int i=0; i<s.size(); i++)
35         if(s[i] != s[s.size()-i-1])
36             return false;
37     return true;
38 }
39 
40 int main()
41 {
42     int k,i;
43     string s,t;
44     cin >> s >> k;
45     for(i=0; i<k; i++)
46     {
47         if(IsPalin(s))
48             break;
49         t = s;
50         reverse(t.begin(), t.end());
51         s = Add(s,t);
52     }
53     cout << s;
54     printf("\n%d",i);
55 
56     return 0;
57 }

 

posted @ 2019-07-11 20:26  林東雨  阅读(173)  评论(0编辑  收藏  举报