Last active
August 10, 2022 16:00
-
-
Save Husseinhj/65ff9fe287618d3c39db7ed8f1b11389 to your computer and use it in GitHub Desktop.
You are given a very large integer n, represented as a string, and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number.
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 org.kotlinlang.play | |
import java.math.BigInteger | |
fun main() { | |
val input = mapOf( | |
-999 to -5999, | |
999 to 9995, | |
9643 to 96543 | |
) | |
val added = 5 | |
input.keys.forEach { | |
val result = maxValue(it, added) | |
println(result) | |
} | |
} | |
fun maxValue(N: Int, K: Int): String { | |
val digits = N.toString().toCharArray() | |
val probability = mutableListOf<BigInteger>() | |
val hasSign = digits.first() == '-' | |
val startFrom = if (hasSign) 1 else 0 | |
for (index in startFrom until digits.size) { | |
val startNumber = digits.copyOfRange(0, index) | |
val endNumber = digits.copyOfRange(index, digits.size) | |
val newNumber = mutableListOf<Char>() | |
newNumber.addAll(startNumber.toList()) | |
newNumber.add(index, ('0' + K)) | |
newNumber.addAll(endNumber.toList()) | |
probability.add(newNumber.toCharArray().joinToString("").toBigInteger()) | |
} | |
probability.add("$N$K".toBigInteger()) | |
return probability.max().toString() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Playground:
https://pl.kotl.in/x4HUYVIrD
Leetcode:
https://leetcode.com/problems/maximum-value-after-insertion/submissions/