-
Notifications
You must be signed in to change notification settings - Fork 154
/
plus-one.js
41 lines (38 loc) · 852 Bytes
/
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
/**
* Plus One
*
* 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.
*
* Example 1:
*
* Input: [1,2,3]
* Output: [1,2,4]
* Explanation: The array represents the integer 123.
*
* Example 2:
*
* Input: [4,3,2,1]
* Output: [4,3,2,2]
* Explanation: The array represents the integer 4321.
*/
/**
* @param {number[]} digits
* @return {number[]}
*/
const plusOne = digits => {
for (let i = digits.length - 1; i >= 0; i--) {
if (digits[i] === 9) {
digits[i] = 0;
} else {
digits[i]++;
return digits;
}
}
digits.unshift(1);
return digits;
};
export default plusOne;