首页 > 其他 > 详细

PAT-1136(A Delayed Palindrome)字符串处理+字符串和数字间的转换

时间:2020-09-19 18:38:09      阅读:68      评论:0      收藏:0      [点我收藏+]

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;
}

PAT-1136(A Delayed Palindrome)字符串处理+字符串和数字间的转换

原文:https://www.cnblogs.com/GarrettWale/p/13697041.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!