码迷,mamicode.com
首页 > 其他好文 > 详细

1024 Palindromic Number (25 分)

时间:2019-12-01 18:59:57      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:art   ace   ring   加法   hat   bre   tor   tac   name   

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

题目分析:大数加法 把是否进1记录就好了
技术图片
 1 #include<iostream>
 2 #include<vector>
 3 #include<queue>
 4 #include<stack>
 5 #include<algorithm>
 6 #include<string>
 7 using namespace std;
 8 string Add(string s1, string s2)
 9 {
10     int flag = 0;
11     int len = s1.length();
12     for (int i = len - 1; i >= 0; i--){
13         int temp = flag+s1[i] - 0 + s2[i] - 0;
14         if (temp > 9){
15             s1[i] = (temp % 10) + 0;
16             flag = 1;
17         }
18         else {
19             s1[i] = temp + 0;
20             flag = 0;
21         }
22     }
23     if (flag)return 1 + s1;
24     else
25         return s1;
26 }
27 int main()
28 {
29     string N;
30     int K;
31     cin >> N >> K;
32     int i = 0;
33     for (; i < K; i++){
34         string s =N;
35         reverse(s.begin(), s.end());
36         if (s == N)
37             break;
38         else
39             N = Add(N, s);
40     }
41     cout << N << endl << i;
42 }
View Code

 

1024 Palindromic Number (25 分)

标签:art   ace   ring   加法   hat   bre   tor   tac   name   

原文地址:https://www.cnblogs.com/57one/p/11966933.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!