题目摘要:A number that reads the same fromright to left as when read from left to right is called a palindrome. Thenumber 12321 is a palindrome; the number 77778 is not. Of course, palindromeshave neither leading nor trailing zeroes, so 0220 is not a palindrome.
The number 21 (base 10) is not palindromein base 10, but the number 21 (base 10) is, in fact, a palindrome in base 2(10101).
Write a program that reads two numbers(expressed in base 10):
N (1 <= N <= 15)
S (0 < S < 10000)
and then finds and prints (in base 10) thefirst N numbers strictly greater than S that are palindromic when written intwo or more number bases (2 <= base <= 10).
Solutions to this problem do not requiremanipulating integers larger than the standard 32 bits.
题目大意:如果一个数从左往右读和从右往左读都是一样,那么这个数就叫做“回文数”。例如,12321就是一个回文数,而77778就不是。当然,回文数的首和尾都应是非零的,因此0220就不是回文数。
事实上,有一些数(如21),在十进制时不是回文数,但在其它进制(如二进制时为10101)时就是回文数。
编一个程序,从文件读入两个十进制数N (1 <= N <= 15)S (0 < S <10000)然后找出前N个满足大于S且在两种或两种以上进制(二进制至十进制)上是回文数的十进制数,输出到文件上。
本问题的解决方案不需要使用大于32位的整型
输入输出样例:
SAMPLE INPUT (file dualpal.in)
3 25
SAMPLE OUTPUT (file dualpal.out)
26
27
28
解题思路:这题类似回文平方数那题,将数转换进制然后判断是否为回文即可
代码:
#include<iostream>
#include<cstring>
using namespace std;
void change(int k, int B, char str3[])
{
int a,n,j=0;
while((n=k/B)!=k)
{
a=k%B;
k=n;
if(a>=10)
str3[j++]='A'+(a-10);
else
str3[j++]='0'+a;
}
char *p1,*p2;
char temp;
p1=str3;
p2=str3+j-1;
while(p1<p2)
{
temp=*p1;
*p1=*p2;
*p2=temp;
p1++;
p2--;
}
str3[j]='\0';
}
int check(char str4[])
{
int len=strlen(str4);
char *pstart;
char *pend;
pstart=str4;
pend=str4+len-1;
while((*pstart==*pend)&&(pstart<pend))
{
pstart++;
pend--;
}
if(pstart<pend)
return 0;
else
return 1;
}
main()
{
int N;
int S;
char str[100];
int count1=0;
cin>>N>>S;
for(int j=S+1;;j++)
{
int count2=0;
for(int k=2;k<=10;k++)
{
change(j,k,str);
cout<<str<<endl;
if((check(str))&&(str[0]!='0'))
{
count2++;
}
if(count2>=2)
{
cout<<j<<endl;
count1++;
break;
}
}
if(count1==N)
break;
}
return0;
}
解题感想:一开始以为只要有一个进制是回文既满足条件,后来才发现题目要求至少在两种进制下是回文,看清题目真的很重要