【HDU 1887】Weird Numbers(負進位轉換)

來源:互聯網
上載者:User

標籤:

傳送門:http://acm.hdu.edu.cn/showproblem.php?pid=1887

題意:有兩種操作,from-r n代表把一個-r進位下的數字n轉換成10進位,to-r n代表把一個10進位下的數字n轉化成-r進位。

分析:兩種操作中from操作很容易實現,和轉換成正進位一樣,沒什麼好說的,而to操作我們首先可以像正常轉化一樣進行短除法,舉個例子:

把15轉化為-3進位。短除法並且倒序之後結果為1,-2,0。而我們的進位中是不能出現-2的,所以我們可以這樣考慮,-2這位代表的是-3,而1位代表的是9,我們可以把-2這位加上3,這樣本來應該是-3*-2=6,變成了-3*1=-3,差值為6-(-3)=9,正好為其前面一位1代表的數,這是在1進一位變成2即可,最後轉換完就是2,1,0。

我們可以在做短除法的過程中進行這樣的操作,發現餘數小於0就讓它減去r,同時商加一,最後得到的數列,倒敘就是答案。注意判to的時候如果輸入的是0,需要單獨輸出,在這上wa了一次。

 

代碼:

/* ***********************************************Author        :Torrance_ZHANGCreated Time  :2016/5/2 14:32:09File Name     :ceshi.cpp************************************************ */#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>#include <vector>#include <queue>#include <set>#include <map>#include <string>#include <math.h>#include <stdlib.h>#include <time.h>typedef long long int LL;using namespace std;int main(){    //freopen("in.txt","r",stdin);    //freopen("out.txt","w",stdout);    char op[10];    while(~scanf("%s",op)){        if(!strcmp(op,"end"))            break;        if(op[0]==‘f‘){            int r=op[5]-‘0‘;            if(r==1) r=10;            r*=-1;            char num[100];            scanf("%s",num);            int len=strlen(num);            int res=0,c=1;            for(int i=len-1;i>=0;i--){                res+=c*(num[i]-‘0‘);                c*=r;            }            printf("%d\n",res);        } else{            int r=op[3]-‘0‘;            if(r==1) r=10;            r*=-1;            int num;            scanf("%d",&num);            if(num==0){                printf("0\n");                continue;            }            int res[50]={0};            int cnt=0;            while(num!=0){                int mod=num%r;                num/=r;                if(mod<0){                    mod-=r;                    num++;                }                res[cnt++]=mod;            }            for(int i=cnt-1;i>=0;i--)                printf("%d",res[i]);            puts("");        }    }    return 0;}

 

【HDU 1887】Weird Numbers(負進位轉換)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.