PAT-1024 Palindromic Number (25)

题目大意:将一个数 N 和其倒置数 N1 相加。在规定次数内,判断是否为回文数字,并输出;超过规定次数,输出到规定次数的数字,并输出。

解题思路:模拟。注意一下细节;规定次数可能是 0 或者一些本身是回文的数字,所以判断语句应该放在循环的开头;本方法用的是字符串大数,挺方便的。

题目链接:https://www.patest.cn/contests/pat-a-practise/1024

#include <iostream>              
#include <algorithm>              
#include <set>              
#include <map>              
#include <vector>              
#include <stack>              
#include <queue>              
#include <cmath>   
#include <cstring>           
using namespace std;
//倒置字符串 
void reverseNum(char *a)
{
	int len = strlen(a);
	for(int i=0;i<len/2;++i)
	{
		char tmp;
		tmp = a[i];
		a[i] = a[len-1-i];
		a[len-1-i] = tmp;
	}
}

int main(int argc, char** argv) {
	char N[100],rev[100],cop[100],N1[100];
	int K,cnt = 0;
	scanf("%s %d",N,&K);
	while(1)
	{
		int push = 0;
		int len = strlen(N);
		
		strcpy(N1,N);
		reverseNum(N);
		if(strcmp(N,N1) == 0 || cnt == K)//出条件判断 
		{
			cout << N << endl << cnt << endl;
			break; 
		}	
		strcpy(rev,N);
		strcpy(cop,N);
		reverseNum(rev);
		for(int i=0;i<=len-1;++i)
		{
			int x = rev[i]-'0';
			int y = cop[i]-'0';
			if(x+y+push >= 10)
			{
				N[i] = x+y+push-10 + '0';
				push = 1;
			}
			else
			{
				N[i] = x+y+push + '0';
				push = 0;
			}
		}
		if(push == 1)
			N[len++] = 1+'0'; 
		N[len] = '\0';
		++cnt;
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zhoujian_1943/article/details/79382677