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;
}
posted @   Garrett_Wale  阅读(153)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
点击右上角即可分享
微信分享提示