题目

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$ ( $\le 10^{10}$ ) is the initial numer and $K$ ( $\le 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 $K$ th step and $K$ instead.

Sample Input 1:

1
67 3

Sample Output 1:

1
2
484
2

Sample Input 2:

1
69 3

Sample Output 2:

1
2
1353
3

思路

结合考察大数计算和回文数,和1023题很相似,涉及到的操作有:

  • 翻转
  • 两数相加
  • 判断回文数

相加的函数和1023中翻倍的写法很像,只不过是把当前位乘二换为相加, 因为这道题是和自己的翻转数相加,所以我代码中没有考虑两数长度不同的情况, 在更广泛的应用中,切记要考虑两不同长度的大数相加的处理。

P.S. 我的处理和1023题中也一样,是倒序存储数字的,所以开头结尾要翻转过来才可以。

字符串长度:这道题,字符串长度取得很宽松,实际上极限可能就是60位左右,不要取得过小。

代码

Github最新代码,欢迎交流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <stdio.h>
#include <string.h>

int isPalindromic(char n[])
{
	int len = strlen(n);
	for (int i = 0; i < len / 2; i++)
		if (n[i] != n[len - i - 1])
			return 0;
	return 1;
}

char* reverse(char n[])
{
	char temp;
	int len = strlen(n);
	for (int i = 0; i < len / 2; i++) {
		temp = n[i];
		n[i] = n[len - i - 1];
		n[len - i - 1] = temp;
	}
	return n;
}

/* only works when a and b are of the same length */
void addAtoB(char a[], char b[])
{
	int l, s = 0, len = strlen(a);

	for (int i = 0; i < len; i++) {
		s += (a[i] - '0') + (b[i] - '0');
		l = s / 10;
		s %= 10;
		b[i] = s + '0';

		s = l;
	}

	if (s)
		b[len] = s + '0';
}

int main()
{
	int K, steps;
	char s1[100] = {0}, s2[100] = {0}, *n = s1, *m = s2;

	scanf("%s %d", n, &K);
	reverse(n);

	for (steps = 0; steps < K && !isPalindromic(n); steps++) {
		/* change 'm' into reverse of 'n' */
		strncpy(m, n, 100);
		reverse(m);
		/* add n and reversed n, and keep the result in n */
		addAtoB(m, n);
	}

	printf("%s\n%d", reverse(n), steps);

	return 0;
}