题目描述
回文数是指数字从前往后读和从后往前读都相同的数字。
例如数字 12321 就是典型的回文数字。
现在给定你一个整数 B B B,请你判断 1 ∼ 300 1∼300 1∼300 之间的所有整数中,有哪些整数的平方转化为 B B B 进制后,其 B B B 进制表示是回文数字。
输入格式
一个整数
B
B
B。
输出格式
每行包含两个在
B
B
B 进制下表示的数字。
第一个表示满足平方值转化为 B B B 进制后是回文数字那个数,第二个数表示第一个数的平方。
所有满足条件的数字按从小到大顺序依次输出。
数据范围
2≤
B
B
B≤20,
对于大于 9 的数字,用 A 表示 10,用 B 表示 11,以此类推。
输入样例:
10
输出样例:
1 1
2 4
3 9
11 121
22 484
26 676
101 10201
111 12321
121 14641
202 40804
212 44944
264 69696
简单利用一下短除法,将数作为string
类型存下来,再定义双指针进行回文判断即可。
C++代码
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int b;
char get(int x){
if(x <= 9) return '0' + x;
return x - 10 + 'A';
}
string trans(int n, int b){
string res;
while(n){ //短除法
res += get(n % b);
n /= b;
}
//string记录结果是从个位往前的,所以需要倒一下。
reverse(res.begin(), res.end());
return res;
}
bool check_pali(string num){
int i = 0, j = num.size() - 1;
while(i < j){
if(num[i] != num[j]) return false;
i ++;
j --;
}
return true;
}
int main(){
cin >> b;
for(int i = 1;i <= 300;i ++){
auto num = trans(i * i, b); //b进制的i * i
if(check_pali(num))
cout << trans(i, b) << " " << num << endl;
}
return 0;
}