PAT 1136 A Delayed Palindrome

54 篇文章 1 订阅

原文链接:我的个人博客原题链接

  PAT 1136 A Delayed Palindrome

考点

  字符串处理;大整数加法

思路

  题目要求一个数和它的逆序数进行相加得到一个新的数,判断得到的数是否为回文数。重复这个操作,直到得到回文数。要求在十次操作之内完成。题目给定的数是<=1000位,因此这里不能用普通的加法,必须要使用字符串来表示数字,并实现大数加法。代码如下

代码

#include <bits/stdc++.h>
using namespace std;
string add(string s1){
    string s2 = s1;
    reverse(s2.begin(),s2.end());//反转链表
//  cout<<s1<<"\t"<<s2<<endl;
    string ans(s1.length()+1,'0');
    int t=0,i;//进位
    for(i=0;s1[i];i++){
        t += (s1[i]-'0')+(s2[i]-'0');
        ans[i] = t%10+'0';
        t /= 10;//进位
    } 
    ans[i] = t+'0';
    reverse(ans.begin(),ans.end());
    ans = ans.substr(ans.find_first_not_of('0'));
    cout<<s1<<" + "<<s2<<" = "<<ans<<endl;
    return ans;
} 
//判断是否是回文数 
bool isH(string s){
    int i=0,j=s.length()-1;
    for(;s[i]==s[j];i++,j--);
    if(i>j) return true;
    else return false;
}
//N最大1 
int main(){
    string s1;
    cin>>s1;
    int cnt=0;
    while(++cnt<=10){
        if(isH(s1)){
            cout<<s1<<" is a palindromic number."<<endl;
            return 0;
        }
        s1 = add(s1);
    }
    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、付费专栏及课程。

余额充值