Skip to content

Instantly share code, notes, and snippets.

@Husseinhj
Last active August 10, 2022 18:12
Show Gist options
  • Save Husseinhj/866fa7d9dcd1838829ce3efb87375c48 to your computer and use it in GitHub Desktop.
Save Husseinhj/866fa7d9dcd1838829ce3efb87375c48 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.
package org.kotlinlang.play
fun main() {
val input = mapOf(
-999 to -5999,
999 to 9995,
9643 to 96543,
-132 to -1325
)
val added = 5
input.keys.forEach {
val result = maxValue(it.toString(), added)
println(result)
}
}
fun maxValue(n: String, x: Int): String {
var result: String
val numberLength = n.length
val digits = n.toCharArray()
val until: Int
if (digits.first() != '-') {
val items = digits.withIndex().filter { Character.digit(it.value, 10) < x }
until = if (items.isNotEmpty()) { items.first().index } else { numberLength }
result = digits.copyOfRange(0, until).joinToString("")
} else {
val items = digits.withIndex().filter { t -> Character.digit(t.value, 10) > x }
until = if (items.isNotEmpty()) { items.first().index } else { numberLength }
result = digits.copyOfRange(0, until).joinToString("")
}
result += ('0' + x)
result += digits.copyOfRange(until, numberLength).joinToString("")
return result
}
@Husseinhj
Copy link
Author

Husseinhj commented Aug 10, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment