C - NUMBER BASE CONVERSION (高精度进制转换)

高精度的取余过程如下:
举个例子, 10 10 10进制下的 17 17 17转换为 3 3 3进制.

1 ÷ 3 = 0 … … 1 1\div 3=0……1 1÷3=01

1 × 10 + 7 = 17 1\times 10+7=17 1×10+7=17

17 ÷ 3 = 5 … … ( 2 ) 17\div 3=5……(2) 17÷3=5(2)

( 2 ) (2) (2) 每轮的最后的余数即是每一轮的余数.

05 = 5 05=5 05=5 上一轮的商变为这一轮的被除数类似模拟除法过程.

5 ÷ 3 = 1 … … ( 2 ) 5\div3=1……(2) 5÷3=1(2)

​ $ (2)$

1 ÷ 3 = 0 … … ( 1 ) 1\div 3=0……(1) 1÷3=0(1)

( 1 ) (1) (1)

11 1 3 = 1 × 3 2 + 2 × 3 1 + 2 × 3 0 = 9 + 6 + 1 = 17 111_3=1\times3^2+2\times3^1+2\times3^0=9+6+1=17 1113=1×32+2×31+2×30=9+6+1=17

具体看代码。

AC代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<map>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int N=1e3+5;
char od[N],nw[N];
int a,b,t;
map<char,int>mp;
const char zh[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
void fun(char *od,char *nw,int a,int b){
	char s[N];
	strcpy(s,od);
	int l=strlen(od),k=0;
	for(int i=0;i<l;){//模拟除法取余. 
		int x=0,j=i;
		while(j<l){
			x=mp[od[j]]+x*a;//用前一位的余数*old_base+该位 
			od[j++]=zh[x/b];//作为下一轮的被除数. 
			x%=b;//取余. 
		} 
		nw[k++]=zh[x];//最后的余数作为商. 
		while(od[i]=='0') i++; //去除前导0 
	}
	printf("%d %s\n%d ",a,s,b);
}
int main(){
	scanf("%d",&t);
    for(int i='0';i<='9';i++) //预处理 
        mp[i]=i-'0';
    for(int i='A';i<='Z';i++)
        mp[i]=i-'A'+10;
    for(int i='a';i<='z';i++)
        mp[i]=i-'a'+36;
	while(t--){
		scanf("%d%d%s",&a,&b,&od);
		memset(nw,0,sizeof nw);
		fun(od,nw,a,b);
		int l=strlen(nw); 
		for(int i=0;i<l;i++)
			printf("%c",nw[l-1-i]);
		puts("\n");
	}
	return 0;
}