首页 > 其他 > 详细

UVA11121 Base -2【-2进制】

时间:2019-03-02 20:38:49      阅读:204      评论:0      收藏:0      [点我收藏+]

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
4
1
7
-2
0
Sample Output
Case #1: 1
Case #2: 11011
Case #3: 10
Case #4: 0

问题链接UVA11121 Base -2
问题简述:(略)
问题分析
????-2进制问题。给定10进制数n,将其转换为-2进制。
????需要注意特殊情况,例如n=0时处理。每次用-2作为除数进行取余运算,如果得到-1则需要特殊处理。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++程序如下:

/* UVA11121 Base -2 */

#include <bits/stdc++.h>

using namespace std;

const int BASE = -2;
const int N = 200;
int ans[N], cnt, digit;

int main()
{  
    int t, n, caseno = 0;
    scanf("%d", &t);
    while (t --) {
        scanf("%d", &n);
        cnt = 0;
        if (n == 0)
            ans[cnt++] = 0;
        while (n) {
            digit = n % BASE;
            if (digit == -1)
                digit = 1;
            n = (n - digit) / BASE;
            ans[cnt ++] = digit;
        }

        printf("Case #%d: ", ++caseno);
        for (int i = cnt - 1; i >= 0; i --)
            printf("%d", ans[i]);
        printf("\n");
    }

    return 0;
}

UVA11121 Base -2【-2进制】

原文:https://www.cnblogs.com/tigerisland45/p/10462641.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!