[LC]66题 Plus One (加1)

①英文题目

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.

②中文题目

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

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

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

示例 1:

输入: [1,2,3]

输出: [1,2,4]

解释: 输入数组表示数字 123。

示例 2:

输入: [4,3,2,1]

输出: [4,3,2,2]

解释: 输入数组表示数字 4321。

③思路

   1、分别考虑123进位变成124,考虑109进位变成110,考虑199进位变成200,考虑999进位变成1000。

   2、倒序检测该位是否为9。

   3,最复杂的就是999进位变成1000了。当第0位等于9而且,索引为0时,就要变1000。

④代码

 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 }

⑤心得,第21行的return句子如果写到18行,系统会报错说21行缺少1个return。所以,在21行这种位子,就该有个return,这里的“21行这种位子”指的是,与第二行的左花括号对应的右花括号之前需要放一个返回值句子。

⑥成果:

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.

猜你喜欢

转载自www.cnblogs.com/zf007/p/11531183.html