Convert Number to base 3 String Representation

Objective: Given a number convert it to base 3 representation.

Example:

N = 35
Base 3 representation: 1022

N = 50
Base 3 representation: 1212

Approach:

Till the number is greater than 0, keep dividing it by 3 and append remainder to the result (append it at the beginning of the result)

N = 35, result =””
N = N/3 => 35/3 => 11 remainder =2 So
N = 11, result =”2”
N = N/3 => 11/3 => 3 remainder =2 So
N = 3, result =”22”
N = N/3 => 3/3 => 1 remainder =0 So
N = 1, result =”022”
N = N/3 => 1/3 => 0 remainder =1 So
N = 0, result =”1022

Java Code:



Output:

Base 3 representation of 35: 1022
Base 3 representation of 50: 1212

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

%d bloggers like this: