簡單地把數字累加,直到形成迴文數為止。需要注意的是,就算輸入已經是迴文,仍然需要至少一次的迭代。
A straightforward approach, adding the numbers until a palindrome is formed. Note that even if the input is already a palindrome, it is still necessary to iterate at least once.
UVa Link
#include <iostream>
#include <cstdio>
#include <cstring>
static inline bool isPalindrome(unsigned int n) {
char num[11];
sprintf(num, "%u", n);
int len = strlen(num);
int loop = len / 2;
for (int i = 0; i < loop; i++) {
if (num[i] != num[len - i - 1]) return false;
}
return true;
}
static inline int rev(unsigned int n) {
int newN = 0;
while (n) {
newN = newN * 10 + n % 10;
n /= 10;
}
return newN;
}
int main() {
std::cin.tie(0);
std::ios_base::sync_with_stdio(0);
unsigned int t;
std::cin >> t;
while (t--) {
unsigned int n, i = 0;
std::cin >> n;
do {
n = n + rev(n);
i++;
} while (!isPalindrome(n));
std::cout << i << ' ' << n << '\n';
}
}