24h購物| | PChome| 登入
2011-12-16 07:13:01| 人氣1,063| 回應2 | 上一篇 | 下一篇

[UVA] 11121 - Base -2

推薦 0 收藏 0 轉貼0 訂閱站台

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











作法 : 遞迴

#include<stdio.h>

#include<stdlib.h>
void Base_2(int n) {
    if(n > 0) {
        Base_2(n/(-2));
        printf("%d", n%2);
    }
    if(n < 0) {
        Base_2(n/(-2)+(n%(-2) != 0));
        printf("%d", abs(n%(-2)));
    }
}
int main() {
    int t, C = 0, n;
    scanf("%d", &t);
    while(t--) {
        scanf("%d", &n);
        printf("Case #%d: ", ++C);
        if(n == 0)    puts("0");
        else Base_2(n), puts("");
    }
    return 0;
}

台長: Morris
人氣(1,063) | 回應(2)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA] 11733 - Airports
此分類上一篇:[UVA] 11732 - strcmp() Anyone?

unknown
想請問一下這題的想法是怎麼樣的?
我看不太懂@@
2012-01-12 05:45:16
版主回應
我是把前幾個列出來, 就會發現遞迴了
2012-01-12 07:00:28
unknown
想請問的是7怎麼換算成-2進位?
2012-01-12 16:12:50
版主回應
7(11011) -> -3(1101) -> 2(110) -> -1(11) -> 1(1)

一直消去最後一個 bit
2012-01-12 17:27:59
是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文