-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0066-plus-one.js
77 lines (62 loc) · 1.62 KB
/
0066-plus-one.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Time O(N) | Space O(N)
* https://leetcode.com/problems/plus-one/
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = (digits) => {
add(digits);
carry(digits); /* Time O(N) */
addLeading(digits);/* | Space O(N) */
return digits;
};
var add = (digits) => digits[digits.length - 1] += 1;
var carry = (digits) => {
for (let digit = (digits.length - 1); (0 < digit); digit--) {/* Time O(N) */
const canCarry = (digits[digit] === 10);
if (!canCarry) break;
digits[digit] = 0;
digits[(digit - 1)] += 1;
}
}
const addLeading = (digits) => {
const canCarry = (digits[0] === 10);
if (!canCarry) return;
digits[0] = 1;
digits.push(0);/* Space O(N) */
}
/**
* Time O(N) | Space O(N)
* https://leetcode.com/problems/plus-one/
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = (digits) => {
for (let digit = (digits.length - 1); (0 <= digit); digit--) {/* Time O(N) */
const canCarry = digits[digit] === 9;
if (canCarry) { digits[digit] = 0; continue; }
digits[digit]++;
return digits;
}
digits.unshift(1); /* Time O(N) | Space O(N) */
return digits;
};
/**
* Time O(N) | Space O(N)
* https://leetcode.com/problems/plus-one/
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = function(digits) {
var i = digits.length - 1
while (digits[i] + 1 === 10) {
digits[i] = 0
i -= 1
}
if (i < 0) {
digits.unshift(1)
} else {
digits[i] += 1
}
return digits
};