【PAT乙级】1079 延迟的回文数

给定一个 k+1 位的正整数 N,写成 a​k​​⋯a​1​​a​0​​ 的形式,其中对所有 i 有 0≤a​i​​<10 且 a​k​​>0。N 被称为一个回文数,当且仅当对所有 i 有 a​i​​=a​k−i​​。零也被定义为一个回文数。

非回文数也可以通过一系列操作变出回文数。首先将该数字逆转,再将逆转数与该数相加,如果和还不是一个回文数,就重复这个逆转再相加的操作,直到一个回文数出现。如果一个非回文数可以变出回文数,就称这个数为延迟的回文数。(定义翻译自 https://en.wikipedia.org/wiki/Palindromic_number )

给定任意一个正整数,本题要求你找到其变出的那个回文数。

输入格式:

输入在一行中给出一个不超过1000位的正整数。

输出格式:

对给定的整数,一行一行输出其变出回文数的过程。每行格式如下

A + B = C

其中 A 是原始的数字,B 是 A 的逆转数,C 是它们的和。A 从输入的整数开始。重复操作直到 C 在 10 步以内变成回文数,这时在一行中输出 C is a palindromic number.;或者如果 10 步都没能得到回文数,最后就在一行中输出 Not found in 10 iterations.

输入样例 1:

97152

输出样例 1:

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

输入样例 2:

196

输出样例 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.

个人理解

这题主要是两个小问题,第一个是大整数的加法,还有一个是判断回文数。

所有的数字都用字符串来存储,由于是两个互为reverse的整数相加,所以可以直接从第0位进行加法,最后结果再reverse一下就可以了。其中每位的结果s = (n1 + n2 + c) % 10,每位的进位c = (n1 + n2 + c) / 10,c的初值设为0。注意最后一位的加法可能有进位。

判断回文数只需要将字符串从头开始和从尾开始同时进行检查,如果都相等则为回文数,否则则不是。

代码实现

#include <cstdio>
#include <cstring>
#include <string>
#include <set>
#include <cmath>
#include <algorithm>
#include <iostream>
#define ll long long
#define ep 1e-5
#define INF 0x7FFFFFFF

using namespace std;

// 检查是否是回文数
bool check(string num) {
    int len = int(num.length());
    for (int i = 0, j = len-1; i <= j; i ++, j --) {
        if (num[i] != num[j]) {
            return false;
        }
    }
    return true;
}

// 加法运算
string add(string num, string rev_num) {
    string ret = "";
    int len = int(num.length());
    
    int c = 0;
    for (int i = 0; i < len; i ++) {
        int s = ((num[i]-'0') + (rev_num[i]-'0') + c) % 10;
        c = ((num[i]-'0') + (rev_num[i]-'0') + c) / 10;
        ret += (s + '0');
        if (i == len-1 && c > 0) {
            ret += (c + '0');
        }
    }
    reverse(ret.begin(), ret.end());
    return ret;
}

int main() {
    // 输入原始数字
    string num;
    cin >> num;

    // 进行回文数运算迭代
    int cnt = 0;
    while (!check(num)) {
        cnt ++;
        // 如果迭代次数超过10次输出并结束程序
        if (cnt > 10) {
            cout << "Not found in 10 iterations." << endl;
            break;
        }
        string rev_num = num;
        reverse(rev_num.begin(), rev_num.end());
        cout << num << " + " << rev_num;
        num = add(num, rev_num);
        cout << " = " << num << endl;
    }

    //如果迭代次数小于等于10次说明找到回文数,并输出
    if (cnt <= 10) {
        cout << num << " is a palindromic number." << endl;
    }
    
    return 0;
}

总结

学习不息,继续加油

猜你喜欢

转载自blog.csdn.net/qq_34586921/article/details/83473819