题意:给一个数n,转换为-2进制的数。
解析:因为转换后的每一位数不能为负数,所以考虑如何将每次取模后的负数变为正数,且数为多少。
结论是若取模为负,则加上基数的绝对值,当前的n++。
设当前取模的位 t = n % base (t < 0, base < 0)
当 t - base(t + |base|)计入转换后的数中时, 原数的这个位相当于由 t * base ^ i 变为了 (t - base) * base ^ i。
减少了需要回加,恰好当前n的值+1 = 原n值回加了base^(i + 1)。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#include <climits>
#include <cassert>
#define LL long long
using namespace std;
const int maxn = 1e5 + 10;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
const double pi = 4 * atan(1.0);
const double ee = exp(1.0);
int num[maxn];
int n;
int top;
const int base = -2;
void miner_change()
{
if (n == 0)
{
printf("0\n");
return;
}
top = 0;
while (n)
{
int t = n % base;
n /= base;
if (t < 0)
{
t -= base;
n++;
}
num[top++] = t;
}
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif // LOCAL
int ncase;
scanf("%d", &ncase);
int ca = 1;
while (ncase--)
{
scanf("%d", &n);
printf("Case #%d: ", ca++);
miner_change();
while (top)
{
int t = num[--top];
printf("%d", t);
}
printf("\n");
}
return 0;
}