Created
April 16, 2022 02:02
-
-
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.
This file contains 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
/* | |
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