Last Updated: 16 Mar, 2021

Base 58

Easy
Asked in companies
FacebookUber

Problem statement

You are given a number N. Your goal is to convert the number into base 58.

The Base58 alphabet consists of the following characters: “123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz”

Each byte value from 0 to 57 maps to the alphabet above.

Conversion Eg: ( according to above mapping).

Base 10 | Base 58
0       |     1  
1       |     2  
10      |     A  
20      |     L
30      |     W 
53      |     u 
Input Format:
The first line of the input contains ‘T’ denoting the number of test cases.

The first and the only line of each test case contains an integer N.
Output Format:
For each test case, print a single line containing a single integer denoting the number in the base 58.

The output of each test case will be printed in a separate line.

Note:

You do not need to input or print anything, as it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 50
0 <= N <= 10 ^ 4

Time limit: 1 sec.

Approaches

01 Approach

You can represent the integers as powers of 58 and then convert them using the above mapping.

 

Eg: 4364 =  1 * (58 ^ 2)+ 17 * (58 ^ 1) + 14 * (58 ^ 0)

1 in base 10 = 2 in base 58, 17 in base 10 = 2 in base J, 14 in base 10 = 2 in base F

Therefore the answer will be: 2JF

 

Algorithm:

  • If the number itself is 0, the answer is 1, else we do the following until the number reaches 0.
    • First, we Initiate an empty string res = ““:
    • We take the remainder of N from 58, and convert it according to the encoding in base 58 and prepend it into res.
      • res= x  + res  , x is the converted character.
    • We divide the number N by 58 and repeat the above step until N reaches 0.