UVa 11121 Base -2(负数进制)
题意:
给定一个大于等于0的整数n,求n的-2进制数。
思路:
1. 对于2进制的,大家都是熟悉的: a[i] = n % 2; n = n/2;
2. 是否发现上面少了一个地方呢?n = n/2是否应该写成 n = (n-a[i])/2 ?这其实是利用了C语言取整的一个特性.
3. 如果对于-2进制,不要偷懒就是了: a[i] = n % 2; n = (n-a[i])/2. 等等还少了什么a[i]必须为正,
所以a[i] = n % 2要改成 a[i] = (n % 2 + 2) % 2;
#include <cstdio>
#include <cstring>
#include <cstring>
int a[50];
void solve(int n)
{
memset(a, 0, sizeof(a));
int i;
for (i = 0; i < 40; ++i)
{
a[i] = (n % 2 + 2) % 2;
n = (n - a[i]) / (-2);
}
for (i = 40; i > 0; --i)
if (a[i]) break;
while (i >= 0)
printf("%d", a[i--]);
printf("\n");
}
int main()
{
int cases, count = 0;
scanf("%d", &cases);
while (cases--)
{
int n;
scanf("%d", &n);
printf("Case #%d: ", ++count);
solve(n);
}
return 0;
}
-------------------------------------------------------
kedebug
Department of Computer Science and Engineering,
Shanghai Jiao Tong University
E-mail: kedebug0@gmail.com
GitHub: http://github.com/kedebug
-------------------------------------------------------