PKU1220 NUMBER BASE CONVERSION 大整数任意进制转换模板

题目大意:有t组cases。每组给你一个from,to,和串s。将from进制下的串s转化为to进制下的串

题目链接:PKU1220 NUMBER BASE CONVERSION

题目分析:直接对进制转换时的人工方法进行模拟,直到将串s除尽。

 
  
#include < iostream >
#include
< string >
using namespace std;

string idx = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz " ;
int getValue( char ch) // 将字符c转换为相对应的数字
{
if (ch >= ' 0 ' && ch <= ' 9 ' ) return ch - ' 0 ' ;
else if (ch >= ' A ' && ch <= ' Z ' ) return ch - ' A ' + 10 ;
else return ch - ' a ' + 36 ;
}
// 将from进制下的字符串转换为to进制下的整数
string change( string s, int from, int to)
{
string res = "" ;
int r,i,g,t,sum = 1 ,len = s.size();
while (sum != 0 ) // sum作为循环结束标志
{
r
= sum = 0 ;
for (i = 0 ;i < len;i ++ )
{
t
= getValue(s[i]);
sum
+= t; // 统计各位数字和
g = t + from * r;
s[i]
= idx[g / to]; // 存储该进制下的商
r = g % to; // 除n取余
}
if (sum > 0 )
res
= idx.substr(r, 1 ) + res; // 先得到的余数放在低位
}
if (res == "" ) // result为空串表明转换得到的结果为0
res = " 0 " ;
return res;
}

int main(){
string s;
int i,t,from,to;
cin
>> t;
while ( t -- ){
cin
>> from >> to >> s;
cout
<< from << " " << s << endl;
cout
<< to << " " << change(s,from,to) << endl << endl;
}
return 0 ;
}

 

转载于:https://www.cnblogs.com/DreamUp/archive/2010/09/13/1825018.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值