UVa : 355 (The Bases Are Loaded)


// http://uva.onlinejudge.org/external/3/355.html

// @BEGIN_OF_SOURCE_CODE

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <sstream>
#include <set>
#include <math.h>
#define N 1000000
using namespace std;

bool valid (int s, char *a)
{
    int equivalent;

    for ( int i = 0; a [i]; i++ ) {
        if ( isdigit (a [i]) ) equivalent = a [i] - 48;
        else equivalent = a [i] - 55;

        if ( equivalent < 0 || equivalent >= s )
            return false;
    }

    return true;
}

long long power (int i, int j)
{
    long long output = 1;
    for ( int k = 1; k <= j; k++ )
        output *= i;

    return output;
}

long long convertToTen (int s, char *a)
{
    long long sum = 0;
    int len = strlen (a);
    int equivalent;

    for ( int i = len - 1; i >= 0; i-- ) {
        if ( isdigit (a [i]) ) equivalent = a [i] - 48;
        else equivalent = a [i] - 55;

        sum += (equivalent * power (s, len - 1 - i));
    }

    return sum;
}

void tenToDest (int d, long long t)
{
    vector <char> v;
    int equivalent;

    while ( t ) {
        equivalent = t % d;
        if ( equivalent >= 10 ) v.push_back (equivalent + 55);
        else v.push_back (equivalent + 48);
        t /= d;
    }

    reverse (v.begin (), v.end ());

    for ( size_t i = 0; i < v.size (); i++ )
        printf ("%c", v [i]);

    if ( v.size () == 0 ) printf ("0");

    printf (" base %d\n", d);
}

int main ()
{
    char input [1000];

    while ( gets (input) ) {
        int sourceBase;
        int destBase;
        char sourceNum [20];

        sscanf (input, "%d %d %s", &sourceBase, &destBase, sourceNum);

        if ( valid (sourceBase, sourceNum) ) {
            long long tenBase = convertToTen (sourceBase, sourceNum);
            printf ("%s base %d = ", sourceNum, sourceBase);
            tenToDest (destBase, tenBase);
        }
        else printf ("%s is an illegal base %d number\n", sourceNum, sourceBase);

    }

    return 0;
}

// @END_OF_SOURCE_CODE
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s