Topic: Convert the m base number X to the n base number. Output and
input: The first line of input includes two integers: M and N (2<=M, N<=36), and enter a number X in the following line , X is an M base number, now you are required to convert the M base number X to an N base number for output.
Output: Output the number represented by the N-ary system of X.
Sample input
10 2
11
Sample output
1011
Tip: Note that if there are letters when input, the letters are uppercase, and if there are letters when output, the letters are lowercase.
The AC code is as follows:
#include<stdio.h>
#include<string.h>
int main(){
int m,n,i,len,s1[110];
char s[110],ans[110];
char map[]={
"0123456789abcdefghijklmnopqrstuvwxyz"};
while(~scanf("%d%d",&m,&n)){
memset(s1,0,sizeof(s1));
memset(ans,0,sizeof(ans));
scanf("%s",s);
len=strlen(s);
//如果输入的为0,则输出也为0
if(len==1&&s[0]=='0'){
printf("0\n");
continue;
}
//将输入的字符串每一位数转换为对应十进制数存储在数组s1中
for(i=0;i<len;i++){
if(s[i]>='0'&&s[i]<='9')
s1[i]=s[i]-'0';
if(s[i]>='A'&&s[i]<='Z')
s1[i]=s[i]-'A'+10;
}
int k=0;
while(1){
int flag=0;
for(i=0;i<len;i++){
if(s1[i]!=0){
flag=1;
break;
}
}
//如果s1[i]中所有数都为0,则终止
if(flag==0)
break;
//利用辗转相除法
int sum=0;
for(i=0;i<len;i++){
sum=sum*m+s1[i];//相当于将m进制转换为10进制按权展开
sum%=n;//相当于10进制转任意进制的求余
}
ans[k++]=map[sum];//找到最终余数在map数组中的字符并保留结果
int sum1=0;
for(i=0;i<len;i++){
s1[i]+=sum1*m;
sum1=s1[i]%n;
s1[i]/=n;
}
}
for(i=k-1;i>=0;i--)//输出结果
printf("%c",ans[i]);
printf("\n");
}
return 0;
}