Palindromes are numbers that read the same forwards as backwards. The number 12321 is a typical palindrome.
Given a number base B (2 <= B <= 20 base 10), print all the integers N (1 <= N <= 300 base 10) such that the square of N is palindromic when expressed in base B; also print the value of that palindromic square. Use the letters 'A', 'B', and so on to represent the digits 10, 11, and so on.
Print both the number and its square in base B.
PROGRAM NAME: palsquare
INPUT FORMAT
A single line with B, the base (specified in base 10).
SAMPLE INPUT (file palsquare.in)
10
OUTPUT FORMAT
Lines with two integers represented in base B. The first integer is the number whose square is palindromic; the second integer is the square itself.
SAMPLE OUTPUT (file palsquare.out)
1 1 2 4 3 9 11 121 22 484 26 676 101 10201 111 12321 121 14641 202 40804 212 44944 264 69696
开始的时候WA了很多次啊,要不就是基数没转成对应进制而是依然按十进制输出了;要不就是字符串转化后忘记再倒叙输出了。说明自己理解题意的能力很有问题啊,哎,OJ上的表述总是让我那么费解。。。
PS->开始我是把字符串当成string处理的,但是发现在赋值的时候根本无法赋值,实在不解原来代码是这样的
1 string tricker;
2 string tricker_i;
3
4 //.......中间省略
5
6 void trans(int init,string target)
7 //短除法转换,储存的顺序为顺序,不是最后结果
8 {
9 int j = -1;
10 int mod, div;
11 target = "";//每次转化都将先前的清空
12 do
13 {
14 mod = init%base;
15 target[++j] = map[mod];
16 //我在这插入了cout << target << endl;每次输出都是空,WHY??
17 init = init/base;
18 }while(init != 0);
19
20 return;
21 }
/*
ID: qyxiang1
PROG: palsquare
LANG: C++
*/
#include <fstream>
#include<string>
#include<iostream>
#include<memory.h>
#include<algorithm>
#include<vector>
#include<string.h>
using namespace std;
ifstream fin("palsquare.in");
ofstream fout("palsquare.out");
#ifdef _DEBUG
#define out cout
#define in cin
#else
#define out fout
#define in fin
#endif
int base;
char tricker[20];
char tricker_i[15];
char map[] =//map数组对应需要的各个数位
{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J'};
void trans(int init,char target[])
//短除法转换,储存的顺序为顺序,不是最后结果
{
int j = -1;
int mod, div;
memset(target,'\0',sizeof(target));//每次转化都将先前的清空
do
{
mod = init%base;
target[++j] = map[mod];
init = init/base;
}while(init != 0);
return;
}
bool is_palindromic(string target)
{
int len = target.size() - 1;
int j ;
for(j = 0; j < len; ++j, --len)
{
if(target[j] != target[len])
return false;
}
return true;
}
int main()
{
in >> base;
int square[301];
int i, j;
for(i = 1; i < 301; ++i)
square[i] = i*i;
int len;
for(i = 1; i < 301; ++i)
{
trans(square[i],tricker);
//转化后判断,满足回文是要将基数也转化为对应进制
if(is_palindromic(tricker))
{
trans(i,tricker_i);
len = strlen(tricker_i);
for(j = len-1; j >=0; --j)//转化后的基数在字符串中为倒序,需要逐个输出
out << tricker_i[j];
out << ' ' << tricker << endl;//乘方数为回文字符串,直接输出就行
}
}
return 0;
}