`
从此醉
  • 浏览: 1044788 次
  • 性别: Icon_minigender_1
  • 来自: US
社区版块
存档分类
最新评论

判断一个数在2-16进制下是否为回文 Palindrom Numbers

 
阅读更多

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


//============================================================================
// Name        : 算法.cpp
// Author      : 
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;

int main() {
	int x;

	cin >> x;

	while(x){
		bool isPali = false;
		char arr[30];
		int base[17] = {0};
		for(int i=2; i<=16; i++){

			int temp = x;
			int len = 0;
			while(temp){
				arr[len++] = temp % i;
				temp /= i;
			}
			bool tag = true;
			/*for(int j=0,k=len-1; j<k; j++,k--){
				if(arr[j] != arr[k]){
					tag = false;
					break;
				}
			}*/
			//第二种写法
			for(int j=0; j<len/2 && tag; j++)
				if(arr[j] != arr[len-j-1])
					tag = false;
			if(tag){
				base[i] = 1;
				isPali = true;
			}
		}

		if(!isPali)
			cout << "Number "<< x <<" is not a palindrom" << endl;
		else{
			cout << "Number "<< x <<"is palindrom in basis at:";
			for(int i=2; i<=16; i++){
				if(base[i])
					cout <<i << " ";
			}
		}

		cin >> x;
	}
	return 0;
}




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics