PAT (Advanced Level) Practice
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 (≤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.
Sample Input 1:
67 3
Sample Output 1:
484
2
Sample Input 2:
69 3
Sample Output 2:
1353
3
个人代码:
#include <cstdio>
#include <cstring>
int pNum[1000];
struct BigNum {
int P[1000];
int len;
BigNum () {
memset(P, 0, sizeof(P));
len = 0;
}
} bigN;
bool isPalin () { //判断是否是Palin
bool flag = true;
int left = 0, right = bigN.len - 1;
while (left < right) {
if (bigN.P[left] != bigN.P[right]) {
flag = false;
break;
}
left ++;
right --;
}
return flag;
}
void add () { //将一个数与其本身倒序相加,暂存在pNum中
int carry = 0; //进位
for (int i = 0; i < bigN.len; i++) {
int temp = bigN.P[i] + bigN.P[bigN.len - 1 - i] + carry;
carry = temp / 10;
pNum[i] = temp % 10;
}
if (carry) {
pNum[bigN.len] = carry;
bigN.len ++;
}
for (int i = 0; i < bigN.len; i++) { //将pNum复制给bigN.P
bigN.P[i] = pNum[i];
}
}
int main () {
int k, step = 0; //规定步骤和已经进行的步骤
char str[20];
scanf("%s %d", str, &k);
bigN.len = strlen(str);
for (int i = 0; i < bigN.len; i++) { //按地位到高位将数字字符串存入数组P中
bigN.P[bigN.len - 1 - i] = str[i] - '0';
}
bool flag; //1代表是Palin
flag = isPalin ();
while (flag == 0 && step < k) {
add ();
flag = isPalin ();
step ++;
}
for (int i = 0; i < bigN.len; i++) {
printf("%d", bigN.P[bigN.len - 1 - i]);
}
printf("\n%d", step);
return 0;
}
思路提示:
需要用数组写,并且数组需要开大一点。