1. 程式人生 > >NOI:1712 數值轉換

NOI:1712 數值轉換


解題思路:以10進製為中間轉換,無論什麼進位制都轉換成10進位制,然後由十進位制進行轉換

注意:當輸入0時的輸出應該也為0

         得到b進位制時按照輾轉相除的方法,從後往前輸出,順序注意

         輸入的字串注意小寫和大寫的處理

#include <stdio.h>
#include <iostream>
#include <string>
#include <cmath>
#include <vector>
using namespace std;
//將數轉成10進位制,然後再進行轉換
long tmp;//中間結果,10進位制
vector<char> tt;//最後結果
int a,c;
string b;
void test(){//轉成十進位制
    for(int i=b.size()-1;i>=0;i--){
        int j=b.size()-1-i;
        if(!isdigit(b[i])){
            if(b[i]<='z'&&b[i]>='a'){//小寫字母
                int d=b[i]-'a'+10;
                tmp+=pow(a,j)*d;
            }else{//大寫字母
                int d=b[i]-'A'+10;
                tmp+=pow(a,j)*d;
            }
        }else{//數字
            int d=b[i]-'0';
            tmp+=pow(a,j)*d;
        }
    }
}
void test2(){//轉換成b進位制時是從後開始得到
    while(tmp!=0){
        int set=tmp%c;
        char t;
        if(set>=10){
            set=set-10;
            t=set+'A';//得到字母
        }else{
            t=set+'0';
        }
        tt.push_back(t);
        tmp=tmp/c;
    }
}
int main(){
    cin>>a>>b>>c;
    if(b!="0"){//注意當輸入0時的處理
    test();//轉換成10進位制
    test2();//轉換成b進位制
    for(int i=tt.size()-1;i>=0;i--){//按從後往前的方向輸出
        cout<<tt[i];
    }
    cout<<endl;
    }else{
        cout<<0<<endl;
    }
}