-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy path66.go
54 lines (51 loc) · 1.23 KB
/
66.go
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
package easy_collection
/**
* 66. Plus One
* <p>
* Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
* <p>
* 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.
* <p>
* You may assume the integer does not contain any leading zero, except the number 0 itself.
* <p>
* Example 1:
* <p>
* Input: [1,2,3]
* Output: [1,2,4]
* Explanation: The array represents the integer 123.
* <p>
* Example 2:
* <p>
* Input: [4,3,2,1]
* Output: [4,3,2,2]
* Explanation: The array represents the integer 4321.
* <p>
* Example 3:
* <p>
* Input: [9,9]
* Output: [1,0,0]
* Explanation: The array represents the integer 99.
*/
func plusOne(digits []int) []int {
digits = reverseDigits(digits)
for i, n := range digits {
if n+1 <= 9 {
digits[i] = n + 1
digits = reverseDigits(digits)
return digits
}
digits[i] = 0
}
digits = append(digits, 1)
digits = reverseDigits(digits)
return digits
}
func reverseDigits(digits []int) []int {
newDigits := make([]int, 0)
digitsLen := len(digits)
for digitsLen > 0 {
digitsLen--
newDigits = append(newDigits, digits[digitsLen])
}
return newDigits
}