POJ1220 Number Base Conversion

题意

Write a program to convert numbers in one base to numbers in a second base. There are 62 different digits:
{ 0-9,A-Z,a-z }
HINT: If you make a sequence of base conversions using the output of one conversion as the input to the next, when you get back to the original base, you should get the original number.

分析

参照某神犇的代码。

此代码异常简洁,本来我想先转十进制在转其他的,没想到可以直接做。

代码

POJ最近炸了,只好在openjudge百练上交了。

#include<bits/stdc++.h>
#define rg register
#define il inline
#define co const
template<class T>il T read(){
    rg T data=0,w=1;
    rg char ch=getchar();
    while(!isdigit(ch)){
        if(ch=='-') w=-1;
        ch=getchar();
    }
    while(isdigit(ch))
        data=data*10+ch-'0',ch=getchar();
    return data*w;
}
template<class T>il T read(rg T&x){
    return x=read<T>();
}
typedef long long ll;

co int N=1000;
int t[N],A[N];
char str1[N],str2[N];
int n,m;
void solve(){
    int len=strlen(str1);
    for(int i=len;i>=0;--i)
        t[len-1-i]=str1[i]-(str1[i]<58?48:str1[i]<97?55:61);
    int k;
    for(k=0;len;){
        for(int i=len;i>=1;--i){
            t[i-1]+=t[i]%m*n;
            t[i]/=m;
        }
        A[k++]=t[0]%m;
        t[0]/=m;
        while(len>0&&!t[len-1]) --len;
    }
    str2[k]=0;
    for(int i=0;i<k;++i)
        str2[k-1-i]=A[i]+(A[i]<10?48:A[i]<36?55:61);
}
int main(){
//  freopen(".in","r",stdin);
//  freopen(".out","w",stdout);
    int kase=read<int>();
    while(kase--){
        read(n),read(m);
        scanf("%s",str1);
        solve();
        printf("%d %s\n%d %s\n\n",n,str1,m,str2);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/autoint/p/10395256.html