PAT-1136(A Delayed Palindrome)字串處理+字串和數字間的轉換
阿新 • • 發佈:2020-09-19
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; }