当时看的时候挺懵逼的,想了一会没想出正解,之后就去百度了一波。
负进制数转换:和正进制一样,每次取的余数保证在0到m-1之间。(例如m=-16,则余数应该在0到15)就可以直接输出。所以用系统的“%”运算符的时候必须注意检查是不是在该范围(可能在m+1到0),否则就调整。调整的方法是:如果余数<0,那么:余数-=m;商++;
// ============================================================
// #pragma GCC optimize(2)
// #pragma GCC optimize(3,"Ofast","inline")
// ============================================================
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <bitset>
#include <map>
#include <utility>
using namespace std;
const int maxn=1e6+10;
const int INF=0x3f3f3f3f;
const int mod=1e9+7;
const double eps=1e-6;
//
template<class T>
inline void read(T &res)
{
char c;
T flag=1;
while((c=getchar())<'0'||c>'9') if(c=='-') flag=-1; res=c-'0';
while((c=getchar())>='0'&&c<='9') res=res*10+c-'0'; res*=flag;
}
template<class T>
void write(T res)
{
if(res<0) res=-res,putchar('-');
if(res>=10) write(res/10);
putchar('0'+res%10);
}
//
char digit[20]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J'};
char ans[maxn];
int x[maxn];
int cnt=0;
void solve(int num,int k)
{
if(num==0)return;
else
{
if(num>0||num%k==0)
{
solve(num/k,k);
cout << digit[num%k];
return;
}
else
{
solve(num/k+1,k);
cout << digit[-k+num%k];
return;
}
}
}
int main()
{
clock_t c1 = clock();
/*----------------------------------------------------------*/
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
//============================================================
#ifdef LOCAL
freopen("in.in","r",stdin);
freopen("out.out","w",stdout);
#endif
//============================================================
int num,k;
cin >> num >> k;
cout << num << "=";
solve(num,k);
cout << "(base" << k << ")";
end:
cerr << "Time Used:" << clock()-c1 << "ms" << endl;
return 0;
}
没有技巧的数学知识又增加了~~