Created
October 22, 2022 08:23
-
-
Save gonaumov/8308079e15d8425212522896670677ce to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package converter | |
import java.math.BigInteger | |
private const val MAXIMUM_OCTAL_SYSTEM = 10 | |
private const val CAPITAL_LETTER_A = 64 | |
class NumberConverter( | |
private val sourceBase: BigInteger, | |
private val targetBase: BigInteger | |
) { | |
private fun convertFromDecimal(decimalNumber: String): String { | |
var tempNumber = decimalNumber.toBigInteger() | |
var result = "" | |
do { | |
val currentResult = tempNumber.divideAndRemainder(targetBase)[1] | |
result += if (currentResult >= MAXIMUM_OCTAL_SYSTEM.toBigInteger()) { | |
(CAPITAL_LETTER_A.toBigInteger().plus(currentResult - (MAXIMUM_OCTAL_SYSTEM.toBigInteger() - BigInteger.ONE))).toString() | |
} else { | |
currentResult.toString() | |
} | |
tempNumber = tempNumber.divide(targetBase) | |
} while (tempNumber >= BigInteger.ONE) | |
return result.reversed() | |
} | |
/** | |
* This function converts the input string to decimal number | |
* system | |
*/ | |
private fun convertToDecimal(numberInput: String): String { | |
var result = BigInteger.ZERO | |
for (i in numberInput.indices) { | |
// leftIndex is the index of current symbol from | |
// left to right. | |
// EG: | |
// In number 123456 if `i` is equal to zero | |
// it will be 6 | |
val leftIndex = (i - numberInput.lastIndex) * -1 | |
val currentSymbol = numberInput[i] | |
// \u0030 and \u0039 are the UTF codes of the numbers | |
// 0 and 9 | |
result += if (currentSymbol in '\u0030'..'\u0039') { | |
currentSymbol.toString().toBigInteger() * sourceBase.pow(leftIndex) | |
} else { | |
val number = 9 + (currentSymbol.code - CAPITAL_LETTER_A) | |
number.toBigInteger() * sourceBase.pow(leftIndex) | |
} | |
} | |
return result.toString() | |
} | |
fun convert(input: String): String { | |
val decimalNumber = convertToDecimal(input) | |
return convertFromDecimal(decimalNumber) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment