Palindrom Numbers

来源:互联网 发布:石家庄桥西网络花店 编辑:程序博客网 时间:2024/04/28 20:11

FJNU.1827

Description
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
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
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

My Program

#include<iostream>
#define N 16
using namespace std;
bool pal[N];

void BasePalindrom(int n)
{
    
int i,j,k,x;
    
char s[32];
    
for(i=2;i<=N;i++)
    
{
        pal[i
-1]=true;
        x
=n;k=0;
        
while(x>0)
        
{
            
if(i>10)
                
switch(x%i)
            
{
                
case 10:s[k]='A';break;
                
case 11:s[k]='B';break;
                
case 12:s[k]='C';break;
                
case 13:s[k]='D';break;
                
case 14:s[k]='E';break;
                
case 15:s[k]='F';break;
                
default:s[k]=x%i+'0';
            }

            
else
                s[k]
=x%i+'0';
            x
/=i;
            k
++;
        }

        
for(j=0;j<k/2;j++)
            
if(s[j]!=s[k-1-j])
            
{
                pal[i
-1]=false;
                
break;
            }

    }

}


int main()
{
    
int i,n;
    
bool flag;
    
while(cin>>n)
    
{
        flag
=false;
        
if(n==0)
            
break;
        BasePalindrom(n);
        
for(i=2;i<=N;i++)
            
if(pal[i-1]&&!flag)
            
{
                cout
<<"Number "<<n<<" is palindrom in basis "<<i;
                flag
=true;
            }

            
else
                
if(pal[i-1])
                    cout
<<" "<<i;
        
if(!flag)
            cout
<<"Number "<<n<<" is not a palindrom";
        cout
<<endl;
    }

    
return 0;
}

YOYO's Note:
 读入数,先转换为2~16进制,转换完就开始判断是否是回文,当是的时候输出结果。
判断完flag没有变化则说明任何进制下都不是回文。注意输出格式。
另外,转换到11~16进制时因为用到了ABCDEF,所以用字符数组存储……(其实MS用普通数组也可以)

原创粉丝点击