Convert a number from Base B1 to Base B2 without using any intermediate base

后端 未结 7 1613
执笔经年
执笔经年 2021-02-02 15:47

Is there a way Convert a number from Base B1 to Base B2 without using any intermediate base.

Ex:

214 from base 5 to base 16 without converting it first to decima

相关标签:
7条回答
  • 2021-02-02 16:32

    Perhaps you could create a class to represent each base. The class would have a series of fields to represent each digit - for instance a Decimal class would have a units field, a tens field, a hundreds field and so on. Then write mutators to add or subtract one from the value represented by the object (and handle carrying between fields), and an accessor that allows you to check if the value is zero. Create an object in the base of and with the value of the input number (maybe write a method that parses a string?) and an object in the desired base with the value of zero. Then have a loop where you subtract one from the input number and add one to the output number until the input number reaches zero.

    If you create the objects by parsing strings, you arguable avoid the problem aioobe points out that you are representing the numbers as binary, although you're arguably using a unary representation. With a little thought you could also make the base class sufficiently generic to handle number of arbitrary bases.

    0 讨论(0)
提交回复
热议问题