大意:将一个十进制的数转换成-2进制的数。
思路:
与转换为2进制类似,只不过迭代时,当n为负数的时候,n % base的值可能为-1,而我们不允许-1出现,则把-1替换为-1 -= base;而替换之后减少的那一部分的值需要在迭代的时候加回来。
有一个人讲的比较清楚:http://www.cnblogs.com/scau20110726/archive/2012/12/21/2828420.html
我们可以把这个推广到任意负数进制的转换。
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
using namespace std;
const int base = -5;
const int MAXN = 100010;
int n;
int stack[MAXN];
void read_case()
{
scanf("%d", &n);
}
void solve()
{
read_case();
if(!n) { printf("0\n"); return ; }
int top = 0;
while(n)
{
int t = n % base;
n /= base;
if(t < 0)
{
t -= base;
n++;
}
stack[top++] = t;
}
while(top)
{
int t = stack[--top];
printf("%d", t);
}
printf("\n");
}
int main()
{
int T, times = 0;
scanf("%d", &T);
while(T--)
{
printf("Case #%d: ", ++times);
solve();
}
return 0;
}
任意负数进制的转换:
void solve()
{
read_case();
if(!n) { printf("0\n"); return ; }
int top = 0;
while(n)
{
int t = n % base;
n /= base;
if(t < 0)
{
t -= base;
n++;
}
stack[top++] = t;
}
while(top)
{
int t = stack[--top];
printf("%d", t);
}
printf("\n");
}