yxc yyds
我是菜狗呜呜呜呜,他的方法好妙
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int b;
int get(int x)
{
if(x<=9)return x+'0';//转换此时的数就是倒取得到的进制数,余数是0到9表明是转为10进制以下
return x+'A'-10;
}
string base(int a,int b)
{
string x;
while(a)x+=get(a%b),a/=b;
reverse(x.begin(),x.end());
return x;
}
bool check(string ans)
{
for(int i=0,j=ans.size()-1;i<j;i++,j--)
{
if(ans[i]!=ans[j])
return false;
}
return true;
}
int main()
{
cin>>b;
for(int i=1;i<=300;i++)
{
auto ans=base(i*i,b);
if(check(ans))
cout <<base(i,b)<<' '<<ans<<endl;
}
return 0;
}
进制转换的核心(拙见)
采用字符串拼接方式,以二进制为桥梁,进行转换;
细节:以十六转八为例,得到二进制的十六进制数之后,先倒序取出,因为可能存在需要补零的情况,补完零后再倒序取出才是正序的二进制数,之后通过substr(i,3)(第i个之后三位)判定,来变成八进制数,因为可能存在前导零的情况,可以继续用
substr(1,len-1)(抓去第一个到len-1为止
code
#include <cstdio>
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
string get_two(string a) {
//int j=0;
string s1 = "";
int len = a.size();
for (int i = 0; i < len; i++ ) {
switch (a[i]) {
case '0':
s1 += "0000";
break;
case '1':
s1 += "0001";
break;
case '2':
s1 += "0010";
break;
case '3':
s1 += "0011";
break;
case '4':
s1 += "0100";
break;
case '5':
s1 += "0101";
break;
case '6':
s1 += "0110";
break;
case '7':
s1 += "0111";
break;
case '8':
s1 += "1000";
break;
case '9':
s1 += "1001";
break;
case 'A':
s1 += "1010";
break;
case 'B':
s1 += "1011";
break;
case 'C':
s1 += "1100";
break;
case 'D':
s1 += "1101";
break;
case 'E':
s1 += "1110";
break;
case 'F':
s1 += "1111";
break;
}
}
//cout << "1,s1:" << s1 ;
return s1;
}
string get_eight(string s) {
string s1 = "", s2 = "", s3 = "";
for (int i = s.length() - 1; i >= 0; i--) { //逆序
s1 += s[i];
}
//cout << "s1:" << s1 << endl;
if (s1.length() % 3 != 0) {//补零
for (int i = 0; i < (3 - (s.length() % 3)); i++) {
s1 += "0";
}
}
//cout << "s1:" << s1 << endl;
for (int i = s1.length() - 1; i >= 0; i--) {
s2 += s1[i];
}
//cout << "s2:" << s2 << endl;
for (int i = 0; i < s2.length(); i += 3) {
if (s2.substr(i, 3) == "000")
s3 += "0"; //提取i之后的三个字符(包括k)
else if (s2.substr(i, 3) == "001")
s3 += "1";
else if (s2.substr(i, 3) == "010")
s3 += "2";
else if (s2.substr(i, 3) == "011")
s3 += "3";
else if (s2.substr(i, 3) == "100")
s3 += "4";
else if (s2.substr(i, 3) == "101")
s3 += "5";
else if (s2.substr(i, 3) == "110")
s3 += "6";
else if (s2.substr(i, 3) == "111")
s3 += "7";
}
if (s3.substr(0, 1) == "0") {
s3 = s3.substr(1, s3.length() - 1);
}
//cout << "s3:" << s3 << endl;
return s3;
}
int main() {
int n;
cin >> n;
string two_n, eight_num;
string a[n];
for (int i = 0; i < n; i++) {
cin >> a[i];
}
for (int i = 0; i < n; i++) {
two_n = get_two(a[i]);
eight_num = get_eight(two_n);
//cout << two_n << endl;
cout << eight_num << endl;
}
return 0;
}