java 版本 和 c++ 版本 实现
总体思想:
- 将1~300的数字变成指定进制的字符(因为进制可能会很长,所以用字符类型).
- 取余从上到下读取,所以要反转一下.
- 判断这个字符串是否是回文(双指针从两边到中间遍历一遍)
c++ 版本
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 300;
// 定义一个变量储存
int n;
// 检查是否是回文
bool isPalindrome(string str)
{
for(int i = 0 , j = str.size() - 1; i < j; i++ , j--)
{
if(str[i] != str[j]) return false;
}
return true;
}
// 进制转换
string IntoTheSystem(int h){
string res;
while(h){
// 取余
int a = h%n;
//
if(a>=10) res += (a-10)+'A';
else res += a+'0';
h=h/n;
}
reverse(res.begin() , res.end());
return res;
}
int main(){
cin>>n;
// 循环N次
for(int i = 1;i<=N;i++){
int h= i*i;
// 将h转化为B进制
string Into =IntoTheSystem(h);
// 判断是否是回文字符
if(isPalindrome(Into)) {
cout << IntoTheSystem(i) << ' ' << Into << endl;
}
}
return 0;
}
java 版本
import java.util.Scanner;
public class Main {
static int Base;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Base = sc.nextInt();
for(int i = 1;i<=300;i++){
// 求它的平方
int square = i * i;
// 将这个数转化为进制
String s = XBase(square);
// 判断X进制是不是回文字符
if(isPalindrome(s)){
System.out.print(XBase(i));
System.out.print(" ");
System.out.println(s);
}
}
}
/**
* 判断是否是回文
* @param s
* @return
*/
private static boolean isPalindrome(String s) {
for(int i = 0 , j = s.length() - 1; i < j; i++ , j--)
{
if(s.charAt(i) != s.charAt(j)) return false;
}
return true;
}
/**
* 转化为 Base 进制的函数
* @param square
* @return
*/
private static String XBase(int square) {
//
String res = "";
while (square>0){
int remainder = square % Base;
if(remainder>=10) {
char c='A';
c = (char) ((char) (remainder-10)+c);
res+=c;
}
else res +=remainder;
square = square / Base;
}
return reverse1(res);
}
/**
* 字符反转的函数
* @param str
* @return
*/
public static String reverse1(String str) {
return new StringBuilder(str).reverse().toString();
}
}