14. Add a simple algorithm swift

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/huanglinxiao/article/details/91529088

Given a non-negative integer nonempty array of integers represented, on the basis of the number plus one.

Most significant digit stored in the first array, each element of the array stores a number only.

You may assume that in addition to the integer 0, the integer does not begin with a zero.

Example 1:

Input: [1,2,3]
Output: [2,4]
Explanation: numeral 123 denotes the input array.
Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: input array represents a number 4321.

solution:

  func plusOne(_ digits: [Int]) -> [Int] {
        var  list = digits
        
        for (index,value) in list.enumerated().reversed() {
        
            if (value == 9) {
                list[index] = 0;
                if index > 0 {
                    list[index-1] += 1
                }else{
                    list[index] = 10
                }
            }else{
                if index == list.count-1 {
                    list[index] += 1
                }
                return list
            }
        }
        
        if (list[0] == 10) {
            list[0] = 0;
            list.insert(1, at: 0)
            return list;
        }
        return list
    }

 

Guess you like

Origin blog.csdn.net/huanglinxiao/article/details/91529088