【PAT乙級】延遲的迴文數

  • 2019 年 11 月 8 日
  • 筆記

版權聲明:本文為部落客原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。

本文鏈接:https://blog.csdn.net/weixin_42449444/article/details/88080527

題目描述:

給定一個 k+1 位的正整數 N,寫成

​​⋯

​​

​​ 的形式,其中對所有 i 有 0≤

<10 且

>0。N 被稱為一個迴文數,當且僅當對所有 i 有

=

。零也被定義為一個迴文數。

非迴文數也可以通過一系列操作變出迴文數。首先將該數字逆轉,再將逆轉數與該數相加,如果和還不是一個迴文數,就重複這個逆轉再相加的操作,直到一個迴文數出現。如果一個非迴文數可以變出迴文數,就稱這個數為延遲的迴文數。(定義翻譯自 https://en.wikipedia.org/wiki/Palindromic_number

給定任意一個正整數,本題要求你找到其變出的那個迴文數。

輸入描述:

輸入在一行中給出一個不超過1000位的正整數。

輸出描述:

對給定的整數,一行一行輸出其變出迴文數的過程。每行格式如下:

A + B = C

其中 A 是原始的數字,BA 的逆轉數,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.

解題思路:

題目已經說的很清楚了,要是輸入的數字是個迴文數就直接輸出" is a palindromic number.",否則將這個數翻轉後再與原數相加得到一個新數。要是新數是迴文數就輸出,新數依舊不是迴文數就繼續相加,10步以內沒有得到迴文數就輸出"Not found in 10 iterations."。需要注意的是字元串相加時的進位,字元串用printf輸出時要用c_str()將string型轉換成char*型。

AC程式碼:

#include <bits/stdc++.h>  using namespace std;    string add(string str)  {  	string temp = str;  	reverse(temp.begin(),temp.end());  	int len = str.length();  	int carry = 0;   //進位  	string result = "";  	for (int i = 0; i < len; i++)  	{  		int num = (str[i]-'0' + temp[i]-'0') + carry;  		carry = 0;  		if(num >= 10)  		{  			carry = 1;  			num -= 10;  		}  		result += char(num + '0');  	}  	if(carry == 1)  	{  		result += '1';  	}  	reverse(result.begin(),result.end());  	return result;  }    int main()  {  	string str;  	cin >> str;  	int cnt = 0;  	while(cnt < 10)  	{  		string temp = str;  		reverse(temp.begin(),temp.end());  		if(temp == str)  		{  			printf("%s is a palindromic number.n",str.c_str());  			break;  		}  		else  		{  			printf("%s + %s = %sn",str.c_str(),temp.c_str(),add(str).c_str());  			str = add(str);  			cnt++;  		}  	}  	if(cnt == 10)  	{  		cout << "Not found in 10 iterations." << endl;  	}  	return 0;  }