算法笔记 — 数制转换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37345402/article/details/83658678

题目链接:http://codeup.cn/problem.php?cid=100000579&pid=1

题目描述

求任意两个不同进制非负整数的转换(2进制~16进制),所给整数在long所能表达的范围之内。
不同进制的表示符号为(0,1,...,9,a,b,...,f)或者(0,1,...,9,A,B,...,F)。

输入

输入只有一行,包含三个整数a,n,b。a表示其后的n 是a进制整数,b表示欲将a进制整数n转换成b进制整数。a,b是十进制整数,2 =< a,b <= 16。

输出

可能有多组测试数据,对于每组数据,输出包含一行,该行有一个整数为转换后的b进制数。输出时字母符号全部用大写表示,即(0,1,...,9,A,B,...,F)。

样例输入

4 123 10

样例输出

27

提示

用字符串存储和表示不同进制的数。

#include<iostream>
#include<cstring>
using namespace std;
typedef long long ll;
char str[1111];
char ans[1111];
ll to_d(ll a){
	int len=strlen(str);
	ll sum=0;
	int x;
	int cnt=1;
	for(int i=len-1;i>=0;i--){
		if(str[i]>='0'&&str[i]<='9'){
			x=str[i]-'0';
		}else if(str[i]>='A'&&str[i]<='F'){
			x=str[i]-'A'+10;
		}else{
			x=str[i]-'a'+10;
		}
		sum+=x*cnt;
		cnt*=a;
	}
	return sum;
}
void to_other(ll sum,ll b){
	int cnt=0;
	do{
		int temp=sum%b;
		if(temp<10){
			ans[cnt++]=temp+'0';
		}else{
			ans[cnt++]=temp+'A'-10;
		}
		sum/=b;
	}while(sum!=0);
	for(int i=cnt-1;i>=0;i--){
		cout<<ans[i];
	}
	cout<<endl;
}
int main(){
	ll a,b;
	while(~scanf("%ld%s%ld",&a,&str,&b)){
		ll d=to_d(a);
		to_other(d,b);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/m0_37345402/article/details/83658678