P1017 进制转换

P1017 进制转换

题解

短除法进制转换

当取模数为负数???

 加上上面的操作就可以防止取模结果为负数啦

代码

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<string>
#include<cstring>
#include<queue>
#include<cmath>

using namespace std;
typedef long long ll;

inline int read()
{
    int ans=0;
    char last=' ',ch=getchar();
    while(ch<'0'||ch>'9') last=ch,ch=getchar();
    while(ch>='0'&&ch<='9') ans=ans*10+ch-'0',ch=getchar();
    if(last=='-') ans=-ans;
    return ans;
}

const int maxn=1e5+10;
int tot=0,a[maxn];
int n,m,mod;

int main()
{
    n=read();mod=read();m=n;
    while(n){
        a[++tot]=n%mod;
        n/=mod;
        if(a[tot]<0) a[tot]=(a[tot]+(-mod))%(-mod),n++;
    //    printf("n=%d  a[tot]=%d
",n,a[tot]);    
    }
    printf("%d=",m);
    for(int i=tot;i>=1;i--){
        if(a[i]>9){
            printf("%c",64+a[i]-9);
        }
        else printf("%d",a[i]);
    }
    printf("(base%d)
",mod);
    return 0;
}
原文地址:https://www.cnblogs.com/xiaoyezi-wink/p/11785588.html