Walt - 1 year ago 52

Java Question

This is not a homework problem, I am too old to get home works :)

So, ideally I am trying to convert a number in a given base to another given base.

Can someone please share the logic, then probably I can write the code myself. Not able to find anything online surprisingly.

Answer Source

The answer depends on whether or not you can use a primitive, such as an `int`

or `long`

for your representation.

If you can, the algorithm is reasonably simple: convert the number in base X to a primitive representation, then convert that representation to base Y.

To convert a number to primitive, use this algorithm:

- Make a running total
`res`

, and set it to zero - Go through the string representing the number number in base X left-to-right
- Convert each "digit" (which may be represented by a letter) to its numeric value
- Multiply running total by X, then add the numeric value of the digit to it

To convert back, use this algorithm:

- Make a string builder
- Remove the value of the last digit by obtaining
`digit = num % Y`

- Convert the digit value to digit character (it may be a letter)
- Append the digit character to the string builder
- Drop the last digit from representation by using
`num /= Y`

- Continue while
`num`

is not zero - Reverse the string in the string builder

If your number is too big for a primitive, such as `int`

or `long`

, you need to build a class for holding numbers greater than primitives. I would recommend using `BigInteger`

initially, and then replacing it with your own implementation.