PAT 甲级 1024 Palindromic Number (25分)

A number that will be the same when it is written forwards or backwards is known as a Palindromic Number. For example, 1234321 is a palindromic number. All single digit numbers are palindromic numbers.

Non-palindromic numbers can be paired with palindromic ones via a series of operations. First, the non-palindromic number is reversed and the result is added to the original number. If the result is not a palindromic number, this is repeated until it gives a palindromic number. For example, if we start from 67, we can obtain a palindromic number in 2 steps: 67 + 76 = 143, and 143 + 341 = 484.

Given any positive integer N, you are supposed to find its paired palindromic number and the number of steps taken to find it.

Input Specification:

Each input file contains one test case. Each case consists of two positive numbers N and K, where N (≤10​10​​) is the initial numer and K (≤100) is the maximum number of steps. The numbers are separated by a space.

Output Specification:

For each test case, output two numbers, one in each line. The first number is the paired palindromic number of N, and the second number is the number of steps taken to find the palindromic number. If the palindromic number is not found after K steps, just output the number obtained at the Kth step and K instead.

Sample Input 1:

67 3

Sample Output 1:

484
2

Sample Input 2:

69 3

Sample Output 2:

1353
3
1. 对于输入的n来说,要先判断他本来是不是回文数字,如果是则step = 0
2. 刚开始我判断一个字符串是不是回文串,想的是从中间向左右枚举,这样的话还得分字符串是奇数还是偶数的情况,但是好像最简单的方式是: 判断本身和reverse之后的字符串相不相同 
3. 由于每次相加的字符串的长度一定是相同的,因此可以在原本的字符串相加模板上去除一部分代码
#include<iostream>
#include<algorithm>
using namespace std;

string add(string a,string b){
    string ans = "";
    reverse(a.begin(),a.end());
    reverse(b.begin(),b.end());
    int before = 0,i;
    for (i = 0; i < a.size() && i < b.size(); ++i){
        before = before + a[i] - '0' + b[i] - '0';
        int cur = before % 10;
        ans = ans + char(cur + '0');
        before = before / 10;
    }

    if (before) ans = ans + char(before + '0');

    reverse(ans.begin(),ans.end());

    return ans;
}

bool check(string str){
    string back = str;
    reverse(str.begin(),str.end());
    return str == back;
}

int main(){

    int step,i;
    string n,back_n;
    cin>>n>>step;
    
    if (check(n)){
        cout<<n<<endl<<0;
        return 0;
    }
    
    bool flag;
    for (i = 0; i < step; ++i){
        back_n = n;
        reverse(n.begin(),n.end());
        n = add(back_n,n);
        flag = check(n);
        if (flag) break;
    }
    
    if (flag)
        cout<<n<<endl<<i + 1;
    else cout<<n<<endl<<i;
    
    return 0;

}
发布了423 篇原创文章 · 获赞 38 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_41514525/article/details/105117272