首页 > 代码库 > leetcode--Plus One

leetcode--Plus One

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.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Solution {
    /**very fundamental problem.<br>
     * @author Averill Zheng
     * @version 2014-06-05
     * @since JDK 1.7
     */
    public int[] plusOne(int[] digits) {
       int length = digits.length;
       int[] result = null;
       if(length > 0){
           int[] temp = new int[length + 1];
           int carry = 1;
           for(int i = length - 1; i > -1; --i){
               int sum = digits[i] + carry;
               carry = sum / 10;
               temp[i + 1] = sum % 10;
           }
           if(carry != 0)
               temp[0] = 1;
           if(temp[0] != 0)
               result = temp;
           else{
               result = new int[length];
               for(int i = 1; i < length + 1; ++i)
                   result[i - 1] = temp[i];
           }  
       }
       return result;   
    }
}