Skip to content

Commit d0323e0

Browse files
committed
Plus One
1 parent ab51b7b commit d0323e0

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
|9|[回文数](https://leetcode-cn.com/problems/palindrome-number/)|[JavaScript](./algorithms/palindrome-number.js)|Easy|
99
|14|[最长公共前缀](https://leetcode-cn.com/problems/longest-common-prefix/)|[JavaScript](./algorithms/longest-common-prefix.js)|Easy|
1010
|21|[合并两个有序链表](https://leetcode-cn.com/problems/merge-two-sorted-lists/)|[JavaScript](./algorithms/merge-two-sorted-lists.js)|Easy|
11+
|66|[加一](https://leetcode-cn.com/problems/plus-one/)|[JavaScript](./algorithms/plus-one.js)|Easy|
1112
|136|[只出现一次的数字](https://leetcode-cn.com/problems/single-number/)|[JavaScript](./algorithms/single-number.js)|Easy|
1213
|189|[轮转数组](https://leetcode-cn.com/problems/rotate-array/)|[JavaScript](./algorithms/rotate-array.js)|Medium|
1314
|344|[反转字符串](https://leetcode-cn.com/problems/reverse-string/)|[JavaScript](./algorithms/reverse-string.js)|Easy|

algorithms/plus-one.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// 方法:进位
2+
// 解题思路来自:两数相加
3+
// Reference: https://leetcode-cn.com/problems/add-two-numbers/
4+
5+
/**
6+
* 加一
7+
* @param {number[]} digits
8+
* @return {number[]}
9+
*/
10+
var plusOne = function (digits) {
11+
const lastIndex = digits.length - 1;
12+
// 进位
13+
let curry = 0;
14+
let arr = [];
15+
16+
for (let i = lastIndex; i >= 0; i--) {
17+
let current = digits[i];
18+
19+
if (i === lastIndex) {
20+
current++;
21+
}
22+
const sum = current + curry;
23+
curry = Math.floor(sum / 10);
24+
current = sum % 10;
25+
26+
arr.unshift(current);
27+
}
28+
29+
if (curry) {
30+
arr.unshift(curry);
31+
}
32+
33+
return arr;
34+
};

0 commit comments

Comments
 (0)