问题陈述
我们说一个数字是回文,如果它是从左到右或从右到左读取的正常数字。例如,数字75457是回文。
当然,属性取决于数字的表示基础。数字17在基数10中不是回文,但它在基数2(10001)中的表示是回文。
这个问题的目的是验证一组给定的数字是否是从2到16的任何基的回文。
输入格式
输入由几个整数组成。每一个0<n<50000的数字都以十进制为单位在单独的行中给出。输入以零结束。
输出格式
您的程序必须打印消息Number i is回文,其中i是给定的数字,然后是数字表示为回文的基础。如果该数字在2到16之间的任何基础上都不是回文,则程序必须打印消息number i is not回文。
Sample Input
17
19
0
Sample Output
Number 17 is palindrom in basis 2 4 16
Number 19 is not a palindrom
思路
将该数字依次转换成2进制到16进制。利用双端队列的正向迭代器和反向迭代器,对是否是回文进行判断。用bitset记录该数字在哪个进制中为回文。
AC代码
#include <iostream>
#include <bitset>
#include <deque>
#define AUTHOR "HEX9CF"
using namespace std;
deque<int> dq;
void trans(int x, int y)
{
while (1 < x)
{
dq.push_front(x % y);
x /= y;
}
if (x)
{
dq.push_front(x);
}
}
int main()
{
int n;
bitset<17> bs;
while (1)
{
cin >> n;
if (0 == n)
{
break;
}
bs.set();
for (int i = 2; i <= 16; i++)
{
dq.clear();
trans(n, i);
deque<int>::iterator it = dq.begin();
deque<int>::reverse_iterator rit = dq.rbegin();
for (; it != dq.end(); it++, rit++)
{
// cout << *it << " " << *rit << endl;
if (*rit != *it)
{
bs[i] = 0;
break;
}
}
// cout << i << endl;
}
if (2 >= bs.count())
{
cout << "Number " << n << " is not a palindrom" << endl;
}
else
{
cout << "Number " << n << " is palindrom in basis";
for (int i = 2; i <= 16; i++)
{
if (bs[i])
{
cout << " " << i;
}
}
cout << endl;
}
}
return 0;
}