2015年10月26日 星期一

[HOJ] 60 -2進位

一般短除法後再轉成-2進位

短除法後此時每一位會有0、1、-1、2四種情況
0、1不用管,-1和2討論如何進位
#include<cstdio>
#include<cstring>
#define LL long long
int a[105],st;
bool f;
LL k;
int main(){
    while(~scanf("%lld",&k)){
        if(!k){
            puts("0");
            continue;
        }
        memset(a,0,sizeof(a));
        f=st=0;
        while(k!=0){
            a[st]=k%(-2);
            k/=(-2);
            st++;
        }
        for(int i=0;i<st+2;i++){
            if(a[i]==-1){
                a[i]=1;
                a[i+1]++;
            }
            if(a[i]==2){
                a[i]=0;
                a[i+1]++;
                a[i+2]++;
            }
        }
        for(int i=st+2;i>=0;i--){
            if(a[i])f=true;
            if(f)printf("%d",a[i]);
        }
        puts("");
    }
}

沒有留言:

張貼留言