Plus One leetcode java

题目

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

 

题解

这道题就是实现题。

先对原数组进行处理。从数组最后一位开始往前检查,如果当前数字是<9的,说明你加1无需进位,从循环跳出即可,如果当前数字等于9,说明加1涉及进位,且加1后当前数字应记为0,继续循环处理。

当对原数组处理完后,还需要判断当前第0位是不是已经变为0了,如果已经变为0了说明是类似99+1这种,需要进位。其他则不需要。

一般对数字进行操作的题都要考虑边界,尤其是溢出问题。

 

代码如下:

 1 public int[] plusOne(int[] digits) {
 2             int length;
 3             length = digits.length;
 4             for(int i = length-1; i>=0; i--){
 5                 if(digits[i]<9){
 6                     digits[i]++;
 7                     break;
 8                 }else{
 9                     digits[i]=0;
10                 }
11             }
12             
13             int[] newdigits;
14             if(digits[0]==0){
15                 newdigits = new int[digits.length+1];
16                 newdigits[0]=1;
17                 for(int i=1;i<newdigits.length;i++){
18                     newdigits[i]=digits[i-1];
19                 }
20             }else{
21                 newdigits = new int[digits.length];
22                 for(int i=0;i<digits.length;i++){
23                     newdigits[i]=digits[i];
24                 }
25             }
26              return newdigits;
27         }

 另外一种考虑溢出的解法如下:

 

 1       public int[] plusOne(int[] digits) {
 2             for(int i=digits.length-1;i>=0;i--){
 3                 digits[i] =1+digits[i];
 4                 
 5                 if(digits[i]==10)
 6                     digits[i]=0;
 7                 else
 8                     return digits;
 9             }
10 
11             //don't forget over flow case
12             int[] newdigit = new int[digits.length+1];
13             newdigit[0]=1;
14             for(int i=1;i<newdigit.length;i++){
15                 newdigit[i] = digits[i-1];
16             }
17             return newdigit;
18         }

posted @ 2014-08-03 04:32  爱做饭的小莹子  阅读(5542)  评论(2编辑  收藏  举报