UVaOJ11121 - Base -2

11121 - Base -2
Time limit: 3.000 seconds

 

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 (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

 题目大意:

               给定一个十进制数转化为-2进制。

 解题方法:

    n mod -2 余数可能为-1,0,1,但是不能出现-1,只能有0,1所以将-1变为1,并且商要加1。然后依此迭代直到商为0为止。

     为什么余数要变为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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值