P1017 进制转换

大致题意:

  • 给你一个十进制数n,把他改成r进制数(r是负数)

基本思路:

  • 直接套模板就行,
  • 但是在取模r的时候,结果可能会出现负数,然后就有了WA(QAQ
  • 这时候特判下就好了,
  • 如果取模结果小于0,则商++,取模结果-=r(负负得正,相当于加abs(r))。
  • 然后按照格式输出就好啦。

Code:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <list>
using namespace std;
#define R read()
#define GC getchar()
#define ll long long
#define ull unsigned long long
#define INF 0x7fffffff
#define LLINF 0x7fffffffffffffff
ll read(){
    ll s=0,f=1;
    char c=GC;
    while(c<'0'||c>'9'){if(c=='-')f=-f;c=GC;}
    while(c>='0'&&c<='9'){s=s*10+c-'0';c=GC;}
    return s*f;
}
int n,r;
char ans[100010];
int tot;
char ch[30]={"0123456789ABCDEFGHIJ"};
int main(){
    n=R;r=R;
    printf("%d=",n);//因为n接写下会变化,所以先输出一点
    while(n){
        int temp=n%r;//先记录,否则无法改变
        n/=r;
        if(temp<0){//特判小于0
            temp-=r;//减r(加abs(r))
            ++n;//商++
        }
        ans[++tot]=ch[temp];//记答案
    }
    for(int i=tot;i>=1;--i){//倒输出
        printf("%c",ans[i]);
    }
    printf("(base%d)",r);
    return 0;
}
原文地址:https://www.cnblogs.com/FUXyao/p/12848506.html