I-Base62
I - Base62
PS:一个任意进制转换的大数问题
传送门:Base62
短除法原理:
20(10进制) => 202(3进制)
20 = (2 * 3 ^ 2 + 0 * 3 ^ 1 + 2 * 3 ^ 0)
20 / 3 = 6 ......2 -> 2 * 3 ^ 0
6 / 3 = 2 .......0 -> 0 * 3 ^ 1
2 / 3 = 0 .......2 -> 2 * 3 ^ 2
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
int main()
{
int a, b;
string a_line, b_line;
cin >> a >> b >> a_line;
vector<int> number;
for(auto c: a_line)
{
if(c >= '0' && c <= '9') number.emplace_back(c - '0');
if(c >= 'A' && c <= 'Z') number.emplace_back(c - 'A' + 10);
if(c >= 'a' && c <= 'z') number.emplace_back(c - 'a' + 36);
}
reverse(number.begin(), number.end());
vector<int> res;
while(number.size())
{
int r = 0; //上一位的余数
// 每循环一次做一次短除法
for (int i = number.size() - 1; i >= 0; i --)
{
// 每个位置上处理前都是上一位的余数乘以进制数加上当前位上的数(注意进制为a)
number[i] += r * a;
// 这个位置上的余数为当前位置上的数除以b作为b进制的数
r = number[i] % b;
// 处理完后b进制的i位数
number[i] /= b;
}
res.emplace_back(r);
while(number.size() && number.back() == 0) number.pop_back();
}
reverse(res.begin(), res.end());
for(auto x : res)
{
if(x <= 9) b_line += char(x + '0');
if(x >= 10 && x <= 35) b_line += char(x - 10 + 'A');
if (x >= 36) b_line += char(x - 36 + 'a');
}
cout << b_line;
return 0;
}
如果懒得注册账号,这里有个几乎一模一样的题目
宣传一波Acwing :Acwing124.数的转换
后面有时间会补上Java大数的解法(等我学一波(* ̄3 ̄)╭)

浙公网安备 33010602011771号