和之前一道回文题目差不多,解法还是使用前文的方法。
核心方法参考如下:
View Code
bool is_palindrome(int num,int base){
int reversed = 0,temp=num;
while(temp!=0){
reversed = reversed*base + temp%base;
temp/=base;
}
return (reversed==num);
}
题目完整代码:
View Code
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool is_palindrome(int num,int base){
int reversed = 0,temp=num;
while(temp!=0){
reversed = reversed*base + temp%base;
temp/=base;
}
return (reversed==num);
}
int main() {
ofstream fout("dualpal.out");
ifstream fin("dualpal.in");
int first_n=0,start=0;
fin>>first_n>>start;
int found = 0,pal_count=0;
while(found<first_n){
++start;
pal_count=0;
for(int i=2;i<=10&&pal_count<2;++i){
if(is_palindrome(start,i)){
pal_count++;
cout<<"base :"<<i<<",";
}
if(pal_count==2){
fout<<start<<endl;
found++;
break;
}
}
cout<<start<<":"<<pal_count<<endl;
}
fin.close();
fout.close();
return 0;
}