① 将P进制数x转换为十进制数y
int y = 0, product = 1; //P在循环中会不断乘P,得到1、P、P^2、P^3···
while(x != 0){
y = y = (x % 10) * product; //x % 10是为了每次获取x的个位数
x = x/10; //去掉x的个位数
product = product * P;
}
② 将十进制数y转换为Q进制数z
采用“除基取余”法。即每次将待转换数除以Q,然后将得到的余数作为低位存储,而商则继续除以Q进行上述操作。
int z[40], num = 0;
do{
z[num++] = y % Q;
y = y/Q;
}while(y != 0);
z数组从高位z[num-1]到低位z[0]即为Q进制z。
1. Problem A 又一版 A+B
输入两个不超过整型定义的非负10进制整数A和B(<=231-1),输出A+B的m (1 < m <10)进制数。
输入格式:测试输入包含若干测试用例。每个测试用例占一行,给出m和A,B的值。
当m为0时输入结束。
不难,注意数据长度,应用long long数据类型表示
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
long long a, b, d, num;
long long s;
int res[40];
while (1) {
cin >> d;
if (d == 0) break;
cin >> a >> b;
s = a + b;
num = 0;
do {
res[num] = s % d;
s = s / d;
num++;
} while (s != 0);
for (int i = num - 1; i >= 0; i--) {
cout << res[i];
}
cout << endl;
}
return 0;
}
2. Problem B 数制转换
求任意两个不同进制非负整数的转换(2进制~16进制),所给整数在long所能表达的范围之内。
不同进制的表示符号为(0,1,...,9,a,b,...,f)或者(0,1,...,9,A,B,...,F)。
注意int与char之间的转换,同时,由于单个存储,不需要再进行取商这一操作。
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
char binary[16] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
int toInt(char c) {
for (int i = 0; i < 16; i++) {
if (c == binary[i] || c == binary[i]+32) return i;
}
}
int main() {
int a, b;
string n;
while (cin >> a >> n >>b ) {
string res;
int y = 0, product = 1, num = 0;
//将n转化为十进制数存于y中
for (int i = n.size()-1; i >= 0; i--) {
y = y + toInt(n[i])*product;
product = product * a;
}
//将y转化为b进制
if (b != 10) {
do {
char temp = binary[y % b];
res = res + temp;
num++;
y = y / b;
} while (y != 0);
for (int i = num - 1; i >= 0; i--) {
cout << res[i];
}
cout << endl;
}
else cout << y << endl;
}
return 0;
}
3. Problem C 进制转换
涉及大数取余,待整理
4. Problem D 八进制
输入一个整数(0<=N<=100000),将其转换成八进制数输出。
简单
#include <iostream>
using namespace std;
int main() {
int n;
while (cin >> n) {
int res[20], num = 0;
do {
res[num++] = n % 8;
n = n / 8;
} while (n != 0);
for (int i = num - 1; i >= 0; i--) {
cout << res[i];
}
cout << endl;
}
return 0;
}