PAT甲级刷题之路——A1136 A Delayed Palindrome

PAT A1136 A Delayed Palindrome(20分)

原题如下

A1136 A Delayed Palindrome

题目大意

字符串和自己翻转后的字符串对应的数字相加,直至达到回文串停止,若迭代超过10次也停止。

错误总结

一开始我没看到字符串长度不超过1000,则即使使用long long型也不行,故要使用大整数相加的方法。
先翻转然后相加最后翻转得到
如下:

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

AC代码

#include<iostream>
#include<cstdio>
#include<string>
#include<cctype>
#include<cstring>
//#include<stdlib>
#include<algorithm>
#include<ctime>
#include<cmath>
#include<vector>
#include<cstdlib>
#include<set>
#include<queue>
#include<map>
#include<stack>
#include <unordered_map>
using namespace std;

int main() {
#ifdef testing
	freopen("input.txt", "r", stdin);
#endif
	string str;
	cin >> str;
	string str2;
	int t = 10;
	while (t--) {
		int flag = 0;
		int k = str.length() - 1;
		string temp = str;
		reverse(str.begin(), str.end());
		if (str != temp) {
			flag = 1;
		}
		str = temp;
		if (!flag||str=="0") {
			cout << str << " is a palindromic number.\n";
			break;
		}
		str2 = str;
		reverse(str.begin(), str.end());
		string sum;
		int carry = 0;
		for (int i = 0; i < str.length(); i++) {
			int num =( str[i] - '0') + (str2[i] - '0')+carry;
			carry = 0;
			if (num >= 10) { carry = 1; num -= 10; }
			sum += char(num+'0');
		}
		if (carry == 1)sum += "1";
		reverse(sum.begin(), sum.end());
		cout << str2 << " + " << str << " = " << sum<< endl;
		str =sum;
	}

	if (t == -1) {
		cout << "Not found in 10 iterations." << endl;
	}
	return 0;
}

结语

到了关键时刻了呢!加油!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值