forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0066-plus-one.js
54 lines (43 loc) · 1.25 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
/**
* 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;
};