Plus One

For this problem, the approach is really straightforward, just add 1 to each of the digit and making sure that the carry is considered as well.

class Solution {
    fun plusOne(digits: IntArray): IntArray {
        var carry = 1
        for(i in digits.size - 1 downTo 0) {
            val sum = digits[i] + carry
            carry = sum / 10
            digits[i] = sum % 10
        }
        
        if(carry != 0) {
            val res = IntArray(digits.size + 1)
            res[0] = carry
            for(i in 1 until res.size) {
                res[i] = digits[i - 1]
            }
            return res
        }
        
        return digits
    }
}

Runtime: 264 ms, faster than 28.57% of Kotlin online submissions for Plus One. Memory Usage: 33.7 MB, less than 60.19% of Kotlin online submissions for Plus One.

If at the end, the carry is not zero then we have to create a new array whose size is 1 more than the original array to accommodate for the left most carry that we have to add.