Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

66. Plus One

Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

1
2
3
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

1
2
3
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

Example 3:

1
2
Input: digits = [0]
Output: [1]

給一個1-9數字陣列[8,8],實作十進位器,從右邊開始,當遇到9以下加1,進位要考慮2個情況,一個是陣列內9加1要進到左邊一位[8,9],另一個是超出陣列的進位,像[9,9]再加1 [1,0,0]。

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int[] plusOne(int[] digits) {
// no need carry
for (int i = digits.length - 1; i >=0; i--) {
if (digits[i] != 9) {
digits[i]++;
break;
} else {
digits[i] = 0;
}
}
// Carry
if (digits[0] == 0) {
int[] res = new int[digits.length+1];
res[0] = 1;
return res;
}
return digits;
}
}

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels