UVA 11121 - Base -2 (数论)

探讨负二进制数的转换与应用
本文深入解析了负二进制数的概念及其转换方法,详细介绍了如何将十进制数转换为负二进制数,并讨论了其在计算机科学领域的应用。

Problem D
Base -2 
Input: 
Standard Input

Output: Standard Output

 

The creator of the universe works in mysterious ways. But
he uses a base ten counting system and likes round numbers.

Scott Adams

Everyone knows about base-2 (binary) integers and base-10 (decimal) integers, but what about base -2? An integer n written in base -2 is a sequence of digits (bi), writen right-to-left. Each of which is either 0 or 1 (no negative digits!), and the following equality must hold.

n = b0 + b1(-2) + b2(-2)2 + b3(-2)3 + ...

The cool thing is that every integer (including the negative ones) has a unique base--2 representation, with no minus sign required. Your task is to find this representation.

Input
The first line of input gives the number of cases, N (at most 10000). N test cases follow. Each one is a line containing a decimal integer in the range from -1,000,000,000 to 1,000,000,000.

Output
For each test case, output one line containing "Case #x:" followed by the same integer, written in base -2 with no leading zeros.

Sample Input                       Output for Sample Input

4
1
7
-2
0
Case #1: 1
Case #2: 11011
Case #3: 10

Case #4: 0


题意:把给定的n转化为-2进制数输出。

思路:就是进制转化。。注意取模的时候有出现-1的情况要变成1来处理。

代码:

#include <stdio.h>
#include <string.h>
#include <math.h>
const int MAXN = 222222;
const int base = -2;
int T, n, MOD;
int out[MAXN], outn;

int main() {
	int t = 0;
	scanf("%d", &T);
	while (T --) {
		outn = 0;
		scanf("%d", &n);
		if (n == 0)
			out[outn ++] = 0;
		while (n) {
			MOD = n % base;
			if (MOD == -1)
				MOD = 1;
			n = (n - MOD) / base;
			out[outn ++] = MOD;
		}
		printf("Case #%d: ", ++ t);
		for (int i = outn - 1; i >= 0; i --)
			printf("%d", out[i]);
		printf("\n");
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值