11121 - Base -2
Time limit: 3.000 seconds
The creator of the universe works in mysterious ways. But |
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 (b i) , 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 |
Problemsetter: Igor Naverniouk
Special Thanks: Shahriar Manzoor
转自:http://www.cnblogs.com/scau20110726/archive/2012/12/21/2828420.html
题目大意:
解题方法:
为什么余数要变为1而且能变为1呢,变了之后要怎么做呢?我找了很多博客都没有说原理,只是简单一句话,可能大家都觉得很简单吧,但是我还是想了一段时间才想出来的,所以就写一下原理
我们来看一个10进制转2进制,例子1024
第0次迭代,1024/2=512,1024%2=0 , 试一下把512++变为513,那么逆回去就是1026,多了2,其实就是2^1
第1次迭代,512/2=256,512%2=0,试一下把256++变为257,那么逆回去,就是1028,多了4,其实就是2^2
说到这里应该很清晰了,在第i次迭代后商+1,其实相当于原来的数增加了2^(i+1),这个有什么用呢
n = b0 + b1(-2) + b2(-2)2 + b3(-2)3 + ...
当n为正数的时候,第i次迭代的时候余数为-1的话,那么i一定是奇数(因为余数为正为负只和n的正负有关,而n的正负在除-2的过程中是交替变化的,很容易可以知道当i为奇数的时候,n是负数或0,余数是-1或0)那么对应的位置就应该是 -1*(-2)^i=2^i ,如果变为1,则是1*(-2)^i=-2^i ,所以变为1后相当于减少了2*2^i=2^(i+1),减少了的要加回来啊,怎么加,就在第i次迭代后的商+1,上面说了,第i次迭代后商+1,相当于逆回去加了2^(i+1),所以以这个商继续迭代下去,最后得到的-2进制数就会等于原来的n
源代码:
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int N, nIndex, t;
int arr[110], c;
scanf("%d", &N);
nIndex = 1;
while (N --) {
c = -1, arr[0] = 0;
scanf("%d", &t);
while (t) {
arr[++ c] = t % (-2);
t /= (-2);
if (arr[c] == -1) {
arr[c] = 1;
t ++;
}
}
printf("Case #%d: ", nIndex ++);
while (c > 0) {
printf("%d", arr[c --]);
}
printf("%d\n", arr[0]);
}
return 0;
}