zju1078題解

題目:

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;

}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章