大整数运算(三)(PAT)A1024.Palindromic Number

题目描述:

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.

我的解题模板

代码:

#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
struct bign{
	int d[1000];
	int len;
	bign(){
		memset(d,0,sizeof(d));
		len=0;
	}
};

bign change(char str[]){
	bign a;
	a.len=strlen(str);
	for(int i=0;i<a.len;i++){
		a.d[i]=str[a.len-i-1]-'0';
	}
	return a;
}

void print(bign a){
	for(int i=a.len-1;i>=0;i--){
		printf("%d",a.d[i]);
	}
	printf("\n");
}

bool Judge(bign a){//判断是否回文
	for(int i=0;i<=a.len/2;i++){
		if(a.d[i]!=a.d[a.len-1-i]){
			return false;//对称位置不等,则一定不回文
		}
	}
	return true;//回文
}

bign add(bign a,bign b){//高精度a+b
	bign c;
	int carry=0;//carry是进位
	for(int i=0;i<a.len||i<b.len;i++){
		int temp=a.d[i]+b.d[i]+carry;
		c.d[c.len++]=temp%10;
		carry=temp/10;
	}
	if(carry!=0){
		c.d[c.len++]=carry;
	}
	return c;
}

int main(){
	char str[1000];
	int T,k=0;
	scanf("%s %d",str,&T);//初始数字、操作次数上限
	bign a=change(str);//将字符串转换为bign
	while(k<T&&Judge(a)==false){//不超过操作次数上限且a非回文
		bign b=a;
		reverse(b.d,b.d+b.len);//将b倒置
		a=add(a,b);//a=a+b
		k++;//操作次数+1
	}
	print(a);
	printf("%d\n",k);
	system("pause");
	return 0;
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值