问题感悟:
- 本题目有一点坑就是当只有一位数的时候这是个回文数如
11234456789
,我第一次是使用本题目的方法1524. 最长回文子串但是这样做是有问题的,第一个代码为最初不能AC的代码,因为我使用string类型存储转化后的进制数,若每一位都只有一位数字,则这样是正确的,但是根据本题目的描述,每一位不一定只有一位数,当这一位中存在多位数字的时候在使用这种方法是永远不能AC的,我wa的第一个例子是这个数转化进制后为123456789
,他其实是一个回文数,但是对于该种方法,对每一个char字符进行比较所以一直是No,所以本题目必须使用vector<string>
的方法,对这里边的每一个元素进行枚举!!!!
这是求回文字串的一个重要的易错点
代码1:(WA)
#include<iostream>
#include<cstring>
#include<algorithm>
#include<stack>
#include<vector>
using namespace std;
typedef long long ll;
vector<string>ve;
string change(ll n,ll b){
string res;
stack<string>temp;
while(n){
temp.push(to_string(n%b));
n/=b;
if(n){
temp.push(" ");
}
}
while(!temp.empty()){
ve.push_back(temp.top());
temp.pop();
}
return res;
}
bool word(){
for(int i=0,j=ve.size()-1;i<ve.size();i++,j--){
if(ve[i]!=ve[j])
return false;
}
return true;
}
int main(){
ll n,b;
cin>>n>>b;
string res=change(n,b);
if(word())
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
if(res.size()==0)
res="0";
for(auto &t:ve){
cout<<t;
}
return 0;
}
代码2(AC):
#include<iostream>
#include<cstring>
#include<algorithm>
#include<stack>
#include<vector>
using namespace std;
typedef long long ll;
vector<string>ve;
string change(ll n,ll b){
string res;
stack<string>temp;
while(n){
temp.push(to_string(n%b));
n/=b;
if(n){
temp.push(" ");
}
}
while(!temp.empty()){
ve.push_back(temp.top());
temp.pop();
}
return res;
}
bool word(){
for(int i=0,j=ve.size()-1;i<ve.size();i++,j--){
if(ve[i]!=ve[j])
return false;
}
return true;
}
int main(){
ll n,b;
cin>>n>>b;
string res=change(n,b);
if(word())
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
if(ve.size()==0)
ve.push_back("0");
for(auto &t:ve){
cout<<t;
}
return 0;
}