http://wikioi.com/problem/1042/
负进制(什么*****)
int m=n;
int k=0;
int s;
while(m!=0)
{
s=m/b;
a[k]=m%b;
if(m<0&&a[k]!=0)//这时a[k]会变为负数
{
a[k]=a[k]-b;//转正
s++;//s应该加一
}
m=s;
k++;
}
以-15 -2 为例
k s a[k] m
0 8 1 8
1 -4 0 -4
2 2 0 2
3 -1 0 -1
4 1 1 1
5 0 1 0
所以答案为110001
提供个样例
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
int n,b;
int a[100]={0};
int main()
{
while(scanf("%d%d",&n,&b)==2)
{
memset(a,0,sizeof(a));
int m=n;
int k=0;
int s;
while(m!=0)
{
s=m/b;
a[k]=m%b;
if(m<0&&a[k]!=0)
{
a[k]=a[k]-b;
s++;
}
m=s;
k++;
}
printf("%d=",n);
for(int i=k-1;i>=0;i--)
{
if(a[i]>=10)
{
printf("%c",a[i]-10+'A');
}
else printf("%d",a[i]);
}
printf("(base%d)\n",b);
}
return 0;
}