题目:
Palindrom Numbers
Time Limit: 1 Second Memory Limit: 32768 KB
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
题目大意:大概就是输入十进制数,然后输出这个数在其他进制是否是回文数。就是正着反着看都一样的数。
算法分析:先是输入十进制数,然后用一个长度为16的数组来表示16个进制,先把整个数组置为0,然后把十进制数分别转化为其他进制数,通过将数字倒转各个数字的顺序和原数字比较来确定是否为回文数。
代码:
语言:c
#include<stdio.h>
int main()
{
void palindrom(int a[],int num);
int num,a[16],i;
while(1)
{
for(i=0;i<16;++i)
a[i]=0;
scanf("%d",&num);
if(num==0)
break;
palindrom(a,num);
if(a[0]==0)
printf("Number %d is not a palindrom/n",num);
else
{
i=0;
printf("Number %d is palindrom in basis ",num);
while(a[i])
{
printf("%d",a[i]);
if(a[i+1]!=0)
printf(" ");
++i;
}
printf("/n");
}
}
return 0;
}
void palindrom(int a[],int num)
{
int ispalindrom(int base,int num);
int base,k=0;
for(base=2;base<=16;++base)
{
if(ispalindrom(base,num))
a[k++]=base;
}
}
int ispalindrom(int base,int num)
{
int change(int base,int num,int c[]);
int c1[10000],c2[10000];
int n=change(base,num,c1);
n=change(base,num,c2);
void swap(int c[],int n);
swap(c1,n);
int m=0,i;
for(i=0;i<n;++i)
if(c1[i]!=c2[i])
m=1;
if(m==0)
return 1;
else
return 0;
}
int change(int base,int num,int c[])
{
int i=0;
while(num!=0)
{
c[i++]=num%base;
num/=base;
}
return i;
}
void swap(int c[],int n)
{
int len=n,i,j,m=(n-1)/2;
for(i=0,j=n-1;i<=m;++i,--j)
{
int temp;
temp=c[i];
c[i]=c[j];
c[j]=temp;
}
}