forked from yuyongwei/Algorithms-In-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplusOne.swift
More file actions
52 lines (39 loc) · 1.2 KB
/
plusOne.swift
File metadata and controls
52 lines (39 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//
// plusOne.swift
//
//
// Created by Dong, Anyuan (133) on 2019/4/5.
//
import Foundation
/*
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
*/
//https://leetcode.com/problems/plus-one/description/
class Solution {
func plusOne(_ digits: [Int]) -> [Int] {
guard !digits.isEmpty else {
return []
}
var result = digits
//reverse iterate
var needsPlusOne = true
for index in stride(from: digits.count-1, to: -1, by: -1) {
if needsPlusOne {
result[index] += 1
}
if result[index] >= 10 {
needsPlusOne = true
result[index] -= 10
} else {
needsPlusOne = false
break
}
}
if needsPlusOne {
result.insert(1, at:0)
}
return result
}
}