【简单题】
【题目】
Statement of the Problem
We say that a number is a palindrom if it is the sane when read from left to right or from right to left. For example, the number 75457 is a palindrom.
Of course, the property depends on the basis in which is number is represented. The number 17 is not a palindrom in base 10, but its representation in base 2 (10001) is a palindrom.
The objective of this problem is to verify if a set of given numbers are palindroms in any basis from 2 to 16.
Input Format
Several integer numbers comprise the input. Each number 0 < n < 50000 is given in decimal basis in a separate line. The input ends with a zero.
Output Format
Your program must print the message Number i is palindrom in basis where I is the given number, followed by the basis where the representation of the number is a palindrom. If the number is not a palindrom in any basis between 2 and 16, your program must print the message Number i is not palindrom.
Sample Input
17
19
0
Sample Output
Number 17 is palindrom in basis 2 4 16
Number 19 is not a palindrom
Source: South America 2001
【题意说明】
定义一个数字为回文数字即该数字从左向右读与从右向左读的读数是一样的,比如75457就是一个回文数字。而有些数字在10进制下不是回文,而在其他进制下确是回文,比如17在10进制下不是回文,但是在2进制下的值10001是回文。题目给出多组测试用例,每组一个10进制数,输出该数字在哪些进制(2~16进制中判定即可)下的数值是回文或者在任意进制下都不是回文。
【解答】
(一)分析:只需尝试2~16这15种进制,计算出给定10进制数字在每种进制下的数值判断是否是回文即可。
(二)代码:
#include<iostream>
using namespace std;
int main()
{
int n,ntemp,i,basis,k;
int res[20],reslen,j,temp;//res存储各进制下的数字字串;reslen为字串长度
bool flag,sflag=false;
int m[15];//m数组存储为回文数字串的进制
while(cin>>n)
{
if(n==0)
break;
k=0;
sflag=false;//初始设定数字n的任意进制数串都不为回文
//从2到16进制循环判断哪个进制下的数字为回文
for(basis=2;basis<=16;basis++)
{
ntemp=n;
j=0;
//生成各进制下的数字串res
while(ntemp!=0)
{
res[j++]=ntemp%basis;
ntemp/=basis;
}
flag=true;//假定该进制数字为回文
reslen=j-1;
temp=reslen/2;
for(j=0;j<=temp;j++)
{
if(res[j]!=res[reslen-j])
{
//从res的首尾数字往中间推一旦发现相对应位置的数字不相等,则res不为回文
flag=false;
break;
}
}
if(flag==true)//一旦某个进制数字串为回文,则将该进制记录到m数组
{
sflag=true;
m[k++]=basis;
}
}
if(sflag==true)
{
cout<<"Number "<<n<<" is palindrom in basis ";
for(j=0;j<k-1;j++)
cout<<m[j]<<' ';
cout<<m[k-1]<<endl;
}
if(sflag==false)
cout<<"Number "<<n<<" is not a palindrom"<<endl;
}
return 0;
}
//Accepted
(解于2009/10)