Skip to content

Instantly share code, notes, and snippets.

@Turskyi
Created April 16, 2022 02:02
Show Gist options
  • Save Turskyi/5b66b11a270a2ae3106b451d95ee8fe3 to your computer and use it in GitHub Desktop.
Save Turskyi/5b66b11a270a2ae3106b451d95ee8fe3 to your computer and use it in GitHub Desktop.
Given an array digits that represents a non-negative integer, add one to the number and return the result as an array.
/*
Given an array digits that represents a non-negative integer, add one to the number and return the result as an array.
Ex: Given the following digits...
digits = [1, 2], return [1, 3].
Ex: Given the following digits...
digits = [9, 9], return [1, 0, 0].
* */
fun plusOne(digits: IntArray): IntArray {
for (i: Int in digits.lastIndex downTo 0) {
if (digits[i] != 9) {
digits[i]++
return digits
} else {
digits[i] = 0
}
}
val result = IntArray(digits.size + 1)
result[0] = 1
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment