Last active
August 10, 2022 18:12
-
-
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.
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 | |
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Playground:
https://pl.kotl.in/XbWmjtSHW
Leet code:
https://leetcode.com/problems/maximum-value-after-insertion/submissions/