PAT-1136(A Delayed Palindrome)字符串处理+字符串和数字间的转换
A Delayed Palindrome
PAT-1136
- 我这里将数字转换为字符串使用的是stringstream字符串流
- 扩充:将字符串转换为数字可以使用stoi函数,函数头为cstdlib
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdio>
#include<sstream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
bool ispalindromic(string s){
int len=s.length();
for(int i=0;i<len/2;i++){
if(s[i]!=s[len-i-1])
return false;
}
return true;
}
string add(string first,string last){
reverse(first.begin(),first.end());
reverse(last.begin(),last.end());
string total="";
int c=0;
for(int i=0;i<first.length();i++){
int a=first[i]-'0';
int b=last[i]-'0';
int temp=a+b+c;
total+=((temp%10)+'0');
c=temp/10;
}
if(c!=0){
stringstream now;
now<<c;
string tempc=now.str();
reverse(tempc.begin(),tempc.end());
total+=tempc;
}
reverse(total.begin(),total.end());
return total;
}
int main() {
string s;
cin>>s;
int len=s.length();
string original=s;
if(ispalindromic(original)){
cout<<original<<" is a palindromic number.";
return 0;
}
for(int i=0;i<10;i++){
string temp=original;
string temp1=original;
reverse(temp1.begin(),temp1.end());
original=add(temp,temp1);
cout<<temp<<" + "<<temp1<<" = "<<original<<endl;
if(ispalindromic(original)){
cout<<original<<" is a palindromic number.";
return 0;
}
}
cout<<"Not found in 10 iterations."<<endl;
return 0;
}
Either Excellent or Rusty