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
注意:
1、由于自己C和C++的基础较为薄弱,特此强调一下<string><string.h> 和<cstring>的区别:
       <string.h>是旧的C头文件,对应的是基于char*的字符串处理函数;
       <cstring>是对应于旧C头文件的std版本;
  <string>是包装了std 的C++头文件,对应的是新的string类,是属于STL的范畴。
因此在写C++代码时,如果需要用到字符串处理函数,则使用<cstring>,若只是要用到string类型的数据,则使用<string>,而写C代码时,就需要使用<string.h>。
2、这里也是用字符数组来计算,注意计算当前值和其反转值相加的结果的过程。


代码:
#include<iostream>
#include<cstring>
using namespace std;

int k,step=0;
char n[110]={'\0' };
int len;
int isPalin()
{//judge whether number n is a Palindromic number
	int i;
	for(i=0;i<len/2;i++)
		if(n[i]!=n[len-i-1])
			break;
	if(i<len/2)
		return 0;
	return 1;
}
void findPalin()
{
	if(step==k||isPalin())
	{
		cout<<n<<endl;
		cout<<step<<endl;
		return;
	}
	++step;
	for(int i=0;i<len/2+len%2;++i)//note i<len/2+len%2 here
		n[i]=n[len-i-1]=n[i]+n[len-i-1]- '0';//calculate the sum of n and its reverse
	for(int i=len-1;i>0;--i)
		if(n[i]>'9' )
		{++n[i-1],n[i]-=10;}
		if(n[0]>'9' )
		{ //if the first digit of n is more than 9,that means the length of n increases by 1 digit
			++len;
			n[0]-=10;
			for(int i=len-1;i>0;--i)
				n[i]=n[i-1];
			n[0]= '1';
		}
		findPalin();
}
int main()
{
	cin>>n>>k;
	len=strlen(n);
	findPalin();
	return 0;
}

你可能感兴趣的:(考试,pat,浙江大学)