-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathq066-plus-one.swift
54 lines (45 loc) · 1.47 KB
/
q066-plus-one.swift
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
53
54
//
// q066-plus-one.swift
// leetcode-swift
// Source* : https://leetcode.com/problems/plus-one/
// Category* : Array
//
// Created by Tianyu Wang on 16/7/1.
// Github : http://github.com/wty21cn
// Website : http://wty.im
// Linkedin : https://www.linkedin.com/in/wty21cn
// Mail : mailto:[email protected]
/**********************************************************************************
*
* Given a non-negative number represented as an array of digits, plus one to the number.
*
* The digits are stored such that the most significant digit is at the head of the list.
*
**********************************************************************************/
import Foundation
struct q66 {
class Solution {
func plusOne(_ digits: [Int]) -> [Int] {
var digits = digits
var index = (digits.endIndex - 1)
var adding = 0
digits[index] += 1
while index >= digits.startIndex {
digits[index] += adding
adding = digits[index] / 10
if adding > 0 {
digits[index] %= 10
}
index = (index - 1)
}
if adding > 0 {
digits.insert(adding, at: 0)
}
return digits
}
}
static func getSolution() -> Void {
print(Solution().plusOne([1,9]))
print(Solution().plusOne([9,9]))
}
}