首页 > 代码库 > uva11121- -2进制

uva11121- -2进制

题目链接 http://acm.hust.edu.cn/vjudge/problem/19593

 

解题思路

把数的2进制写出来。

用-2进制套进去,比较两者的关系,可得出结论。

 

代码

#include<stdio.h>#include<string.h> #include<stdlib.h>const int maxLen = 205;int base2[maxLen];void GetBase2(int num, int &w){    while(num != 0) {        base2[++w] = num % 2;        num /= 2;    }}void ChangeBase(int num, int &w){    if(num > 0) {        for(int i=0; i<=w; i++) if(i % 2 == 1) {            int jin = 0, j = i + 1;            if(base2[i]) base2[j]++;             jin = base2[j] / 2; base2[j] %= 2;            while(jin) {                 j++;                base2[j] += jin;                 jin = base2[j] / 2; base2[j] %= 2;             }            w = w > j ? w : j;        }    }    else if(num < 0) {        for(int i=0; i<=w; i++) if(i % 2 == 0) {            int jin, j = i + 1;            if(base2[i]) base2[j]++;             jin = base2[j] / 2; base2[j] %= 2;            while(jin) {                j++;                base2[j] += jin;                 jin = base2[j] / 2; base2[j] %= 2;             }            w = w > j ? w : j;        }    }    else w = 0;}int main(){    int cases, t = 1;    int wei;    scanf("%d", &cases);    while(cases--) {        int number;        wei = -1;        memset(base2, 0, sizeof(base2));        scanf("%d", &number);        GetBase2(abs(number), wei);        ChangeBase(number, wei);        printf("Case #%d: ", t);        for(int i=wei; i>=0; i--) printf("%d", base2[i]);        printf("\n");        t++;    }    return 0;}

 

uva11121- -2进制