title: PAT1136
date: 2021-01-22 20:03:07
tags: PAT
1136
題目:
計(jì)算特殊的Palindrome數(shù)序目,性質(zhì)是ai = ak-i薪前,如果本身不是,則計(jì)算他和自己轉(zhuǎn)置的和是不是情连,最多連續(xù)計(jì)算10次和
范圍:
數(shù)的長(zhǎng)度為1000個(gè)數(shù)字以內(nèi)
分析:
數(shù)的長(zhǎng)度1000內(nèi),所以是個(gè)大數(shù)览效,需要用到大數(shù)加法
解法:
大數(shù)加法算法
- 兩個(gè)數(shù)轉(zhuǎn)置(此題以轉(zhuǎn)置却舀,長(zhǎng)度一樣虫几,不用考慮)
- 從后往前加,每次計(jì)算每一位的和挽拔,加上上一位的進(jìn)位辆脸,加入字符串
- 字符串轉(zhuǎn)置
代碼問題
代碼中的大數(shù)加法沒有處理長(zhǎng)度短的的數(shù)前面有過多的0使長(zhǎng)度大于長(zhǎng)的數(shù)的可能
代碼:
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
bool judge_num(string num){
int len = num.length();
for(int i = 0; i < len/2; i++){
if(num[i] != num[len - i - 1]) return false;
}
return true;
}
string add(string a,string b)
{
string ret="";
int lena=a.size();
int lenb=b.size();
int i=0,j=0;
int c=0;
while(i<lena&&j<lenb)
{
int now=a[i]-'0'+b[i]-'0'+c;
c=now/10;
now=now%10;
char charnow=now+'0';
ret+=charnow;
i++;
j++;
}
while(i<lena)
{
int now=a[i]-'0'+c;
c=now/10;
now=now%10;
char charnow=now+'0';
ret+=charnow;
i++;
}
while(j<lena)
{
int now=b[j]-'0'+c;
c=now/10;
now=now%10;
char charnow=now+'0';
ret+=charnow;
j++;
}
if(c>0)
{
ret+="1";
}
reverse(ret.begin(),ret.end());
return ret;
}
int main(){
freopen("./1136_in", "r", stdin);
string num;
cin>>num;
for(int i = 0; i <= 10; i++){
if(judge_num(num)) {
cout<<num<<" is a palindromic number."<<endl;
break;
}
else if(i <= 9){
string tmp_num = num;
reverse(num.begin(), num.end());
cout<<tmp_num<<" + "<<num<<" = ";
num = add(tmp_num, num);
cout<<num<<endl;
}
else {
cout<<"Not found in 10 iterations."<<endl;
}
}
}