ZeroJudge C015: Reverse and Add

題目敘述

每筆測資第一行有一個正整數N,接下來會有N行,每行會有一個正整數。如果這個數字非迴文,則將這個數字和這個數字反轉之後的值相加,例如195不是迴文,所以要將195加上他的反轉591,一直這個動作直到出現迴文,要求輸出需要進行多少次相加之後才會變成迴文並且該迴文是什麼。


範例輸入 #1

5

195

265

750

2

99

範例輸出 #1

4 9339

5 45254

3 6666

1 4

6 79497


解題思路

每個數字至少需要進行計算一次,所以就算一開始就是迴文了也需要計算下一次出現迴文的時間。可以將收到的資料轉換成字串或是一開始收資料的時候就收成字串型態。使用While迴圈,如果目前的數字不是迴文就一直做計算,並且每次進While迴圈計算的次數就+1。

解題程式碼如下 (僅供參考):

#include <iostream>
#include <algorithm>
using namespace std;

int toint (string str)
{
    if (str.length() == 1) return int(str[0] - '0');
    return stoi(str);
}

int calc (int N)
{
    int a = N;
    string str = to_string(N);
    reverse(str.begin(), str.end());
    int b = toint(str);
    return a + b;
}

bool OK (int N)
{
    string str = to_string(N);
    string str1 = str;
    reverse(str1.begin(), str1.end());
    if (str == str1) return true;
    return false;
}

int main() {
    cin.sync_with_stdio(0);
    cin.tie(0);
    int N;
    cin >> N;
    for (int i = 0; i<N; i++)
    {
        int tmp;
        cin >> tmp;
        int count = 1;
        tmp = calc(tmp);
        while (!OK(tmp))
        {
            count++;
            tmp = calc(tmp);
        }
        cout << count << " " << tmp << "\n";
    }
}

留言

這個網誌中的熱門文章

ZeroJudge M933: 邏輯電路

ZeroJudge A148: You Cannot Pass?!

ZeroJudge A263: 日期差幾天