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;

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章