进制转换
作者:互联网
将M进制的数X转换为N进制的数输出。
输入涉及大数运算,在知道进制转换规则的基础上,进行大数运算,
#include <iostream>
#include <string.h>
#include <cstdio>
#include <vector>
using namespace std;
const int maxn = 1010;
struct bign
{
int d[maxn], len;
bign() {
memset(d, 0, sizeof(d));
len = 0;
}
};
bign mutify(bign n, int x) {
bign c;
c.len = 0;
int carry = 0;
for (int i = 0; i < n.len; i++) {
int temp = n.d[i] * x + carry;
c.d[c.len++] = temp % 10;
carry = temp / 10;
}
while (carry != 0) {
c.d[c.len++] = carry % 10;
carry /= 10;
}
return c;
}
bign add(bign n1, bign n2) {
bign c;
c.len = 0;
int carry = 0;
for (int i = 0; i < n1.len || i < n2.len; i++) {
int temp = n1.d[i] + n2.d[i] + carry;
c.d[c.len++] = temp % 10;
carry = temp / 10;
}
if (carry != 0) {
c.d[c.len++] = carry;
}
return c;
}
bign m2ten(string x, int m) {//m进制变10进制
bign ans;
ans.len = 1;
bign product;
product.d[0] = 1;
product.len = 1;
for (int i = x.size()-1; i >=0 ; i--)
{
int temp;
if (x[i] >= '0' && x[i] <= '9') {
temp = x[i] - '0';
}
else if (x[i] >= 'A' && x[i] <= 'Z') {
temp = x[i] - 'A' + 10;
}
ans = add(ans, mutify(product, temp));
product = mutify(product, m);
}
return ans;
}
bign divide(bign num, int x, int& r) {
bign c;
c.len = num.len;
//从高位开始除
for (int i = num.len - 1; i >= 0; i--) {
r = num.d[i] + r * 10; //被除数的当前位
if (r < x) {//被除数当前位不够除
c.d[i] = 0;
}
else {
c.d[i] = r / x;
r = r % x;
}
}
while (c.len - 1 >= 1 && c.d[c.len - 1] == 0)
c.len--;
return c;
}
void show(bign num) {
for (int i = num.len - 1; i >= 0; i--)
{
if (num.d[i] > 9) {
printf("%c", (char)(num.d[i] - 10 + 'A'));
}
else {
printf("%d", num.d[i]);
}
}
cout << endl;
}
bign ten2n(bign num, int n) {//10进制变n进制
bign ans;
if (n == 10) {
return num;
}
else {
do
{
int r = 0;
num = divide(num, n, r);
ans.d[ans.len++] = r;
} while (!(num.d[0] == 0 && num.len == 1));
}
return ans;
}
int main()
{
int m, n;
string x;
cin >> m >> n>>x;
bign t = m2ten(x, m);
bign res = ten2n(t, n);
show(res);
}
标签:10,转换,进制,temp,int,len,bign,carry 来源: https://www.cnblogs.com/custoyth/p/12726277.html