Wednesday, 10 February 2016

Uva - 10473 - Simple Base Conversion Problem Solution.

Solution:

#include<bits/stdc++.h>
using namespace std;
/*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
int main(){

    int val = 10;
    string num;
    map<char,int>hexVal;
    map<int,char>decVal;
    for(char c = 'A'; c <= 'F'; c++,val++)hexVal[c] = val;
    char c = 'A';
    for(int i = 10; i <= 15; i++,c++)decVal[i] = c;
    while(cin >> num){
        if(num[0] == '-')return 0;
        int len = num.length();
        long long dec = 0,hex,resDec = 0;
        string resHex;
        if(num[1] != 'x'){
            for(int i = 0; i < len; i++)dec = dec *10 + (num[i] - 48);
            while(dec != 0){
                int rem = dec % 16;
                if(rem > 9)resHex += decVal[rem];
                else resHex += (char)(rem) + '0';
                dec/=16;
            }
            reverse(resHex.begin(),resHex.end());
            cout << "0x" << resHex << endl;
        }
        else{
           int p = (len - 1) - 2;
           for(int i = 2; i < len; i++){
                if(num[i] >= 48 && num[i] <= 57)resDec += (num[i]- 48) * pow(16,p);
                else resDec += hexVal[num[i]] * pow(16,p);
                p--;
           }
           cout << resDec << endl;
        }
    }
    return 0;
}

No comments:

Post a Comment