进制转换

高精度进制转换,挺无聊的这种题,非要写个麻烦的高精度。

const int N=110;
struct bignum
{
    int m[N];
    int len;
    bignum()
    {
        memset(m,0,sizeof m);
        len=0;
    }
};
int ra,rb;
string a;
int r;

int get(char x)
{
    if(isdigit(x)) return x-'0';
    return x-'A'+10;
}

char trans(int x)
{
    if(x<10) return '0'+x;
    return 'a'+x-10;
}

bignum mul(bignum a,int b)
{
    bignum c;
    c.len=a.len;
    int carry=0;
    for(int i=0;i<c.len;i++)
    {
        int t=a.m[i]*b+carry;
        c.m[i]=t%10;
        carry=t/10;
    }
    while(carry)
    {
        c.m[c.len++]=carry%10;
        carry/=10;
    }

    while(c.len > 1 && c.m[c.len-1] == 0) c.len--;
    return c;
}

bignum add(bignum a,bignum b)
{
    bignum c;
    c.len=max(a.len,b.len);

    int carry=0;
    for(int i=0;i<c.len;i++)
    {
        int t=a.m[i]+b.m[i]+carry;
        c.m[i]=t%10;
        carry=t/10;
    }
    if(carry) c.m[c.len++]=carry;
    return c;
}

bignum Div(bignum a,int b)
{
    bignum c;
    c.len=a.len;

    r=0;
    for(int i=c.len-1;i>=0;i--)
    {
        r=r*10+a.m[i];
        c.m[i]=r/b;
        r%=b;
    }
    while(c.len > 1 && c.m[c.len-1] == 0) c.len--;
    return c;
}

int main()
{
    while(cin>>ra>>rb)
    {
        string sa;
        cin>>sa;

        bignum a;
        a.m[0]=0,a.len=1;
        bignum base;
        base.m[0]=1,base.len=1;

        for(int i=sa.size()-1;i>=0;i--)
        {
            int t=get(sa[i]);
            //a=base*t+a;
            //base=base*ra
            a=add(mul(base,t),a);
            base=mul(base,ra);
        }

        string res;
        while(a.m[0] != 0 || a.len > 1)
        {
            //a=a/rb;
            a=Div(a,rb);
            res+=trans(r);
        }
        reverse(res.begin(),res.end());
        cout<<res<<endl;
    }
    //system("pause");
    return 0;
}
posted @ 2021-02-15 17:22  Dazzling!  阅读(21)  评论(0编辑  收藏  举报