CodingChillout.Malta: Simple Number Conversion

http://codechillout.sphere-contest.com/problems/onlineround/CONVERT

Converting a number from any base to any base.
Assume that n ≤ 36 and the digits are 0,1,2,3,4,5,6,7,8,9, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z.

Input

The first line contains integer N, the number of test cases.
n s r
n is the number to convert
s is the source base
r is the resulting base

Output

For each n s r, output the number n in r base.

Example

Input:
4
56378 10 2
AB98BC 15 10
ABCDEF123456 36 2
1000100101010 2 10

Output:
1101110000111010
8182977
1001011010111011111010000110001101100010101101000110110111010
4394

import sys

digits ="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def base2base(number,rBase,sBase):
    '''
    # Implementation of Any base to Decimal, but int() is faster
    dec = 0
    for n in number:
        dec = digits.index(n,0,rBase) + dec * rBase
    '''
    dec = int(number,rBase)
    result = []
    while(dec != 0):
        dec,mod = divmod(dec, sBase)
        result.insert(0,digits[mod])
    for i in result:
        sys.stdout.write( "%s" % (i))
    print


instances = int(raw_input())
for v in range(0,instances):
    data = raw_input().split(" ")
    number = data[0]
    rBase = int(data[1])
    sBase = int(data[2])
    if(number != '0'):
       base2base(number,rBase,sBase)
    else:
        print 0

Code on Ideone

Please like & share:

Leave a Reply