题目描述
回文数是指数字从前往后读和从后往前读都相同的数字。
例如数字 12321 就是典型的回文数字。
现在给定你一个整数 B,请你判断 1∼300 之间的所有整数中,有哪些整数的平方转化为 B 进制后,其 B 进制表示是回文数字。
输入格式
一个整数 B。
输出格式
- 每行包含两个在 B 进制下表示的数字。
- 第一个表示满足平方值转化为 B 进制后是回文数字那个数,第二个数表示第一个数的平方。
- 所有满足条件的数字按从小到大顺序依次输出。
数据范围
2 ≤ B ≤ 20,
对于大于 9 的数字,用 A 表示 10,用 B 表示 11,以此类推。
输入样例
输出样例
思路
短除法
程序代码
- 经典写法
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
char get(int x)
{
if(x <= 9)
return x + '0';
return x - 10 + 'A';
}
string base(int n, int b)
{
string num;
while(n)
{
num += get(n % b);
n /= b;
}
reverse(num.begin(), num.end());
return num;
}
bool check(string num)
{
for(int i = 0, j = num.size() - 1; i < j; ++ i, -- j)
if(num[i] != num[j])
return false;
return true;
}
int main()
{
int b;
cin >> b;
for(int i = 1; i <= 300; ++ i)
{
auto num = base(i * i, b);
if(check(num))
cout << base(i, b) << ' ' << num <<endl;
}
return 0;
}
- 使用栈的特性
#include <iostream>
#include <stack>
#include <cstring>
#include <algorithm>
using namespace std;
stack<char> s;
char change(int x) //元素转换
{
if(x <= 9)
return x + '0';
else
return x - 10 + 'A';
}
string convert(int x, int b) //进制转换函数
{
string str;
while(x)
{
s.push(change(x % b)); //将余数转换后压入栈
x /= b;
}
int t = s.size();
while(t--)
{
str += s.top(); //获取栈顶元素
s.pop(); //弹出栈顶元素
}
return str; //返回结果
}
bool check(string s) //判断函数
{
for(int i = 0, j = s.size() - 1; i < j; ++ i, -- j)
if(s[i] != s[j])
return false; //若不满足回文规则,直接结束函数
return true;
}
int main()
{
int b;
cin >> b;
for(int i = 1; i <= 300; ++ i)
{
auto s = convert(i * i, b); //转换
if(check(s)) //判断
cout << convert(i, b) << ' ' << s << endl; //输出结果
}
return 0;
}
- 若有问题,欢迎交流