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
Solution:
// 声明:本代码仅供学习之用,请不要作为个人的成绩提交。
// email: bitrain@hotmail.com
#include <iostream>
#include <vector>
using namespace std;
int main( void ) {
for ( ; ; ) {
int number;
cin >> number;
if ( number == 0 ) {
break;
}
vector< int > result;
for ( int i = 2; i <= 16; ++i ) {
vector< int > newnum;
int num = number;
while ( num != 0 ) {
newnum.push_back( num % i );
num /= i;
}
int left = 0 , right = newnum.size( ) - 1;
for ( ; left < right; ++left , --right ) {
if ( newnum[ left ] != newnum[ right ] ) {
goto NOT;
}
}
result.push_back( i );
NOT:;
}
if ( result.size( ) > 0 ) {
cout << "Number " << number << " is palindrom in basis ";
vector< int >::iterator p = result.begin( );
cout << *p;
++p;
for ( ; p != result.end( ); ++p ) {
cout << " " << *p;
}
cout << endl;
} else {
cout << "Number " << number << " is not a palindrom" << endl;
}
result.clear( );
}
return 0;
}