-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathPlusOne.js
More file actions
66 lines (55 loc) · 1.37 KB
/
Copy pathPlusOne.js
File metadata and controls
66 lines (55 loc) · 1.37 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
* You may assume the integer do not contain any leading zero, except the number 0 itself.
* The digits are stored such that the most significant digit is at the head of the list.
*
* Accepted.
*/
/**
* @param {number[]} digits
* @return {number[]}
*/
let plusOne = function (digits) {
let flag = false;
digits[digits.length - 1]++;
for (let i = digits.length - 1; i >= 0; i--) {
if (flag) {
digits[i]++;
}
if (digits[i] >= 10) {
flag = true;
digits[i] %= 10;
} else {
flag = false;
}
}
if (flag) {
digits.splice(0, 0, 1)
}
return digits;
};
if (plusOne([1]).toString() === [2].toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (plusOne([9]).toString() === [1, 0].toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (plusOne([9, 9]).toString() === [1, 0, 0].toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (plusOne([2, 8, 9, 9, 9]).toString() === [2, 9, 0, 0, 0].toString()) {
console.log("pass")
} else {
console.error("failed")
}
if (plusOne([2, 8, 8, 9]).toString() === [2, 8, 9, 0].toString()) {
console.log("pass")
} else {
console.error("failed")
}