负数做进制数
https://www.luogu.com.cn/problem/P1017
例: 将其转换成-2 进制的时候:
15 = -7 * -2 + 1;能直接写出余数为1,
-15 = 7 * -2 + (-1);此时的余数就变成了-1,不符合我们找余数的规则,但是我们只需要将商加一或者-1就能将其转换成整数
-15 = 8 * -2+1;
由此可见将除数加一能让商除数更小,因为被除数是负数商肯定是正数,除数是负数,当商越大时,商除数越小,让余数余下更多.
#include<iostream>
using namespace std;
int num,R,r;
char result[30] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K'};
char result2[1000];
//将每一位的余数保存下来.
int main(void)
{
cin>>num>>R;
int last =num;
int i;
cout<<num<<"=";
for(i=0;num!=0;i++)
{
//cout<<num;
r = num%R;
//cout<<r<<endl;
if(r<0)
{
r =num-(num/R + 1)*R;
//cout<<num/R<<endl;
num = num/R+1;
}
else num = num/R;
//cout<<" "<<r<<" "<<endl;
result2[i] = result[r];
//cout<<result[r];
}
for(int j=i-1;j>=0;j--)
{
cout<<result2[j];
}
cout<<"(base"<<R<<")" ;
return 0;
}