A1024 Palindromic Number (25 point(s))

数字各位递增,增减排序后相加的数为回文

1. 原文

原题

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 (≤$10^{10}$) is the initial numer and K (≤100) 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:

1
67 3

Sample output 1:

1
2
484
2

Sample Input:

1
69 3

Sample output:

1
2
1353
3

2. 解析

10位数,应该用string,int已不适用

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main(){
string str;
int k;
cin>>str>>k;
int i = 0;
for (; i < k; ++i)
{
string s2 = str;
reverse(s2.begin(),s2.end());

if (str==s2)
{
cout<<str<<"\n"<<i<<endl;
break;
}
string ans;
int carry = 0;
for (int j = str.length()-1; j >= 0; j--)
{
int temp = (str[j]-'0')+(s2[j]-'0')+carry;
ans+=temp%10+'0';
carry=temp/10;
}
if (carry!=0)
{
ans+=carry+'0';
}
reverse(ans.begin(),ans.end());
str = ans;
}
if (i==k)
{
cout<<str<<"\n"<<k<<endl;
}


return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/09/03/A1024/
  • 发布时间: 2019-09-03 12:35
  • 更新时间: 2021-10-29 13:59
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!