Simple Swift solution

  • 0
    func plusOne(_ digits: [Int]) -> [Int] {
            var result = digits
            for i in (0..<result.count).reversed() {
                if result[i] != 9 {
                    result[i] = result[i]+1
                    return result
                } else {
                    result[i] = 0
            if result.first == 0 {
                result.insert(1, at: 0)
            return result

    Explanation: Loop from the end of the array to start. Just add 1 if the digit is not a 9, and return. If digit is a 9, replace it with a 0 and go to the previous digit - rinse an repeat. In the end, check if the first digit of the resulting array is a 0. If it is, that means that the number was of the form 9999... In this case, insert a 1 in the start.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.