PAT甲级1136 A Delayed Palindrome (20分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

Input Specification:

Each input file contains one test case which gives a positive integer no more than 1000 digits.

​​Output Specification:

在这里插入图片描述

Sample Input 1:

97152

Sample Output 1:

97152 + 25179 = 122331
122331 + 133221 = 255552
255552 is a palindromic number.

Sample Input 2:

196

Sample Output 2:

196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
94039 + 93049 = 187088
187088 + 880781 = 1067869
1067869 + 9687601 = 10755470
10755470 + 07455701 = 18211171
Not found in 10 iterations.

二、解题思路

回文数的题,题目提到不会超过1000位,显然不能再用数字的格式存放这些数据,所以我们这里用字符串来处理。用到字符串类型的话,我们就必须手动模拟两个数的加法,这个过程我这里封装成了一个add函数,关键是进位处理问题,以及最后要记得再翻转一次。在主函数中写一个10次的循环,每次循环对应输出即可,如果已经碰到回文数了,就直接return 0。

三、AC代码

#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
using namespace std;
bool check(string str)  //检查一个字符串是否为回文字符串
{
    
    
    int sze = str.size(), k;
    if(sze%2 == 0)  k = sze/2 - 1;
    else    k = sze/2;
    for(int i=0; i<=k; i++)
    {
    
    
        if(str[i] != str[sze - 1 - i])  return false;   //判断第i个和倒数第i个元素是否一致
    }
    return true;
}
string add(string str1, string str2)    //大数加法
{
    
    
    int carry=0, sze = str1.size(); //carry表示进位,初始化为0
    string ans = "";    //存放结果
    for(int i=sze-1; i>=0; i--) //从低位开始计算
    {
    
    
        int tmp = str1[i] - '0' + str2[i] - '0' + carry;    //先计算数字
        carry = 0;
        if(tmp>=10) //数字大于10,进位+1,余数存入结果数组
        {
    
    
            carry = tmp/10;
            tmp %= 10;
        }
        ans += to_string(tmp);
    }
    if(carry != 0)  ans += to_string(carry);    //最后一个进位要记得处理
    reverse(ans.begin(), ans.end());    //翻转这个数组
    return ans;
}
int main()
{
    
    
    string str;
    cin >> str;
    string tmp;
    for(int i=0; i<10; i++)
    {
    
    
        if(check(str))
        {
    
    
            cout << str << " is a palindromic number." << endl;
            return 0;   //找到回文数直接返回
        }
        else
        {
    
    
            tmp = str;
            reverse(tmp.begin(), tmp.end());
            cout << str << " + " << tmp << " = " << add(str, tmp) << endl;
            str = add(str, tmp);
        }
    }
    cout << "Not found in 10 iterations." << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42393947/article/details/109046217
今日推荐