[LC] 66 questions Plus One (plus 1)

① English title

Given a non-empty array of digits representing a non-negative integer, plus 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 contain a single digit.

 

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

 

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.

② Chinese title

Given a non-negative integer nonempty array of integers represented, on the basis of the number plus one.

 

Most significant digit stored in the first array, each element of the array stores only a single digit.

 

You may assume that in addition to the integer 0, the integer does not begin with a zero.

 

Example 1:

 

Input: [1,2,3]

Output: [2,4]

Explanation: The numeral 123 indicates the input array.

Example 2:

 

Input: [4,3,2,1]

Output: [4,3,2,2]

Explanation: Enter the number that represents an array of 4321.

③ ideas

   1, respectively, the carry into consideration 123 124, 109 carry into consideration 110, 199 carry into consideration 200, 999 into consideration becomes 1000 bits.

   2, descending detects whether the bit 9.

   3, the most complex is 999 Carry became the 1000. When Bit 0 is equal to 9 and, if the index is 0, 1000 will change.

④ Code

 1 class Solution {
 2     public int[] plusOne(int[] digits) {
 3         for(int i=digits.length-1;i>=0;i--){
 4              if(digits[i]==9&&i!=0)
 5                 continue;
 6              if(digits[i]==9&&i==0){
 7                 int[] arr=new int[digits.length+1];
 8                 arr[0]=1;
 9                 for(int j=1;j<arr.length;j++){
10                     arr[j]=0;
11                 }
12                 return arr;
13             }
14             if(digits[i]!=9){
15                 digits[i]+=1;
16                 for(int j=i+1;j<digits.length;j++)
17                     digits[j]=0;  
18                 break;
19             }   
20         }
21         return digits;
22     }
23 }

⑤ experience, return the first 21 rows of the sentence if written 18 lines, 21 lines will get an error saying the lack of a return. So, in this line of 21 seats, there is a relation to return, where "this seat row 21" refers to, and before the closing brace brace corresponding to the second row of the need to put a return value sentence.

⑥ achievements:

Runtime:  0 ms, faster than 100.00% of Java online submissions for Plus One.
Memory Usage:  35.4 MB, less than 97.58% of Java online submissions for Plus One.

Guess you like

Origin www.cnblogs.com/zf007/p/11531183.html