PAT A-1136 A Delayed Palindrome

本题链接:1136 A Delayed Palindrome - PAT (Advanced Level) Practice (pintia.cn)

题意:

  给定一个数字a,如该数不是回文数,则将a翻转得到b,判断a+b是否为回文数,如果不是则再次执行翻转并相加,直到结果为回文数,如果十次后得不到回文数则结束。

  本题为经典的大整数运算(因为题中给出数字<=1000digits)

代码:

#include<iostream>
#include<cmath>
#include<string>
#include<algorithm>
using namespace std;

string add(string a,string b) {
	string ans;
	int carry = 0;
	for (int i = 0; i < a.size(); i++) {
		int num = (a[i] - '0') + (b[i] - '0') + carry;
		carry = 0;
		if (num >= 10) {
			num -= 10;
			carry = 1;
		}
		ans += char(num + '0');
	}
	if (carry == 1) ans += '1';
	reverse(ans.begin(), ans.end());
	return ans;
}

int main() {
	string num;
	cin >> num;
	int i = 0;
	
	for (i = 0; i < 10; i++) {
		string rNum = num;
		reverse(rNum.begin(), rNum.end());
		if (num == rNum) {
			cout << num << " is a palindromic number.\n";
			break;
		}else {
			cout << num << " + " << rNum << " = " << add(num, rNum) << endl;
			num = add(num,rNum);
		}
		
	}
	if (i == 10) {
		printf("Not found in 10 iterations.");
	}
	
	return 0;
}

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值