题目

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 Input1:

67 3

Sample Output1:

484
2

Sample Input2:

69 3

Sample Output2:

1353
3

Code:

#include<bits/stdc++.h>
using namespace std;

string n;
void Add(string t){
	int flag=0;
	for(int i=n.length()-1;i>=0;i--){
		//这里参考了柳神代码...柳神yyds!!!
		n[i]=n[i]+t[i]+flag-'0';
		if(n[i]>'9'){
			flag=1;
			n[i]-=10;
		}
		else flag=0;
	}
	if(flag==1) n='1'+n;  //!
}

int main(){
	int k,i;
	cin>>n>>k;
	for(i=0;i<k;i++){
		string tmp=n;
		reverse(n.begin(),n.end());	 //!
		if(n==tmp) break;
		else Add(tmp);
	}
	cout<<n<<endl<<i<<endl;
	
	return 0;
}

记录

  • string模拟大数(一开始用long long出错了…)
  • 字符串长度用length()
  • 最后一个flag需要判断是否为1,如果是1也需要加到字符串中!(不要忽略!)
  • 学习string类型reverse的使用!!reverse(n.begin(),n.end());
  • 不要用中间变量tmp判断位上的数是否大于10!
    int tmp=n[i]+t[i]+flag-'0';//错误
    正确写法:n[i]=n[i]+t[i]+flag-'0';
Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐