[LeetCode] 66. Plus One

You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's.

Increment the large integer by one and return the resulting array of digits.

Example 1:

Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].

Example 2:

Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].

Example 3:

Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].

Constraints:

  • 1 <= digits.length <= 100
  • 0 <= digits[i] <= 9
  • digits does not contain any leading 0's.

加一。

给定一个由 整数 组成的 非空 数组所表示的非负整数,在该数的基础上加一。

最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。

你可以假设除了整数 0 之外,这个整数不会以零开头。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/plus-one
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题意是给一个非空数组,表示一个数字,请对其加一。最优解是从右往左扫,判断当前位置上的数字 digits[i] 是不是 9,两种情况

  • 第一种情况,如果 digits[i] 是 9,就把当前位 digits[i] 变为 0,再接着往下看
  • 第二种情况,就正常对当前位 +1,立即退出循环,返回数组

若是第一种情况,在某一位上遇到了一个 9,那么我们把当前位变为 0,这里的进位其实是隐式地被带到了下一位上。举个例子,比如 input 是 19,当你一开始遇到 9 的时候,把他变为 0;然后下一位遇到 1,此时我们还需要对 1 做 +1 的操作并返回 20。进位在这里其实是隐式地从个位被带到了十位。

还有一种情况,比如 input 是 999。因为在 for 循环里我们没有掉入 return 那一行,所以当我们 for 循环走完,只能说明我们遇到的是一个每一位都是 9 的数字,此时我们需要新开一个数组,比原数组长度多 1。

时间O(n)

空间O(n) - res数组

Java实现

 1 class Solution {
 2     public int[] plusOne(int[] digits) {
 3         // corner case
 4         if (digits == null || digits.length == 0) {
 5             return digits;
 6         }
 7 
 8         // normal case
 9         for (int i = digits.length - 1; i >= 0; i--) {
10             if (digits[i] < 9) {
11                 digits[i]++;
12                 return digits;
13             } else {
14                 digits[i] = 0;
15             }
16         }
17         int[] res = new int[digits.length + 1];
18         res[0] = 1;
19         return res;
20     }
21 }

 

JavaScript实现

 1 /**
 2  * @param {number[]} digits
 3  * @return {number[]}
 4  */
 5 var plusOne = function(digits) {
 6     // corner case
 7     if (digits == null || digits.length == 0) {
 8         return digits;
 9     }
10 
11     // normal case
12     for (let i = digits.length - 1; i >= 0; i--) {
13         if (digits[i] < 9) {
14             digits[i]++;
15             return digits;
16         } else {
17             digits[i] = 0;
18         }
19     }
20     let res = new Array(digits.length + 1).fill(0);
21     res[0] = 1;
22     return res;
23 };

 

LeetCode 题目总结

posted @ 2019-10-10 02:17  CNoodle  阅读(699)  评论(0编辑  收藏  举报