| 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 (≤1010) 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. |
67 3
- 484
- 2
69 3
- 1353
- 3
题目大意
给你一个整数N,求N重复翻转相加多少次后,可以得到第一个回文数,结果输出最先得到的回文数与翻转次数。
本题额外设置了最多翻转次数限制K,如果在翻转K次后还无法形成回文数,输出此时得到整数与K
思路
数组模拟运算,当然这题也可以当字符串来写
- #include
- using namespace std;
- vector<int> nums1,nums2;
- void OP1(); // 反转相加
- bool OP2(int head,int tail); // 回文数判断
- int main()
- {
- long long num,K;
- cin >> num >> K;
- do{
- nums1.push_back(num%10);
- num/=10;
- } while (num);
-
- for(int z=0;z
- if(!OP2(0,nums1.size()-1))OP1();
- else
- {
- K = z;
- break;
- }
- }
- for(int z=nums1.size()-1;z>=0;z--) cout << nums1[z];
- cout << endl << K << endl;
- return 0;
- }
- void OP1()
- {
- int len = nums1.size()-1;
- for(int z=0;z<=len;z++) nums2.push_back(nums1[z]+nums1[len-z]);
- for(int z=0;z
if(nums2[z]>9){ - nums2[z] -= 10;
- nums2[z+1] += 1;
- }
- if(nums2[len]>9){
- nums2[len] -=10;
- nums2.push_back(1);
- }
- nums1.assign(nums2.begin(),nums2.end());
- nums2.clear();
- }
- bool OP2(int head,int tail)
- {
- if(head>=tail) return true;
- if(nums1[head]!=nums1[tail]) return false;
- return OP2(head+1,tail-1);
- }