1024 Palindromic Number (25分)

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:
67 3

Sample Output 1:
484
2

Sample Input 2:
69 3

Sample Output 2:
1353
3

题目误区

不深入思考的话,很容易陷入题目的误区:好像最多只是把100个不超过10^10的数相加。于是开始用long long和stoll做,但是有两个测试点会出现数据溢出的现象,才发现并没有那么简单,因为将一个数倒转之后再相加的增长速度也是很快的。如:
10009+90001=100010。接近于直接乘10,可见其增长速度。因此,尽管是long long型变量也不足以承受这么快的增长速度。还是得用大整数运算的方法

错误示范

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
bool isPalin(long long n) {
	string s = to_string(n);
	for (int i = 0; i <= s.size() / 2 ; i++) {
		if (s[i] != s[s.size()-1 - i]) return false;
	}
	return true;
}
int main() {
	long long n; int k;
	cin >> n >> k;
	int cnt = 0;
	while (!isPalin(n)&&cnt<k) {
		string s = to_string(n);
		reverse(s.begin(), s.end());
		long long t = stoll(s);
		n += t;
		cnt++;
	}
	cout << n << endl << cnt;
	return 0;
}

正解

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
bool isPalin(string s) {
	string t = s;
	reverse(t.begin(), t.end());
	if (t == s) return true;
	else return false;
}
string add(string a) {
	string b = a;
	reverse(b.begin(), b.end());
	string an(a.size(), '0');
	int carry = 0;
	for (int i = a.size() - 1; i >= 0; i--) {
		an[i] = (a[i] - '0' + b[i] - '0' + carry) % 10 + '0';
		carry = (a[i] - '0' + b[i] - '0' + carry) / 10;
	}
	if (carry != 0) an = "1" + an; //字符连接
	return an;
}
int main() {
	string in; cin >> in;
	int k, cnt = 0; cin >> k;
	while (!isPalin(in) && cnt < k) {
		string t = add(in);
		in = t;
		cnt++;
	}
	cout << in << endl << cnt;
	return 0;
}
发布了26 篇原创文章 · 获赞 5 · 访问量 430

猜你喜欢

转载自blog.csdn.net/weixin_43590232/article/details/104077111
今日推荐