【簡單題】
【題目】
Palindrom Numbers Time Limit: 2 Seconds Memory Limit: 65536 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
【題意說明】
定義一個數字為迴文數字即該數字從左向右讀與從右向左讀的讀數是一樣的,比如75457就是一個迴文數字。而有些數字在10進位下不是迴文,而在其他進位下確是迴文,比如17在10進位下不是迴文,但是在2進位下的值10001是迴文。題目給出多組測試案例,每組一個10進位數,輸出該數字在哪些進位(2~16進位中判定即可)下的數值是迴文或者在任意進位下都不是迴文。
【解答】
(一)分析:只需嘗試2~16這15種進位,計算出給定10進位數字在每種進位下的數值判斷是否是迴文即可。
(二)代碼:
#include<iostream>using namespace std;int main(){int n,ntemp,i,basis,k;int res[20],reslen,j,temp;//res儲存各進位下的數字字串;reslen為字串長度bool flag,sflag=false;int m[15];//m數組儲存為迴文數字串的進位while(cin>>n){if(n==0)break;k=0;sflag=false;//初始設定數字n的任意進位數串都不為迴文//從2到16進位迴圈判斷哪個進位下的數字為迴文for(basis=2;basis<=16;basis++){ntemp=n;j=0;//產生各進位下的數字串res while(ntemp!=0){res[j++]=ntemp%basis;ntemp/=basis;}flag=true;//假定該進位數字為迴文reslen=j-1;temp=reslen/2;for(j=0;j<=temp;j++){if(res[j]!=res[reslen-j]){//從res的首尾數字往中間推一旦發現相對應位置的數字不相等,則res不為迴文flag=false;break;}}if(flag==true)//一旦某個進位數字串為迴文,則將該進位記錄到m數組{sflag=true;m[k++]=basis;}} if(sflag==true){cout<<"Number "<<n<<" is palindrom in basis ";for(j=0;j<k-1;j++)cout<<m[j]<<' ';cout<<m[k-1]<<endl;}if(sflag==false)cout<<"Number "<<n<<" is not a palindrom"<<endl;}return 0;}//Accepted
(解於2009/10)