码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode--Plus One

时间:2014-06-07 16:56:28      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:c   class   blog   code   java   a   

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;   
    }
}

  

leetcode--Plus One,布布扣,bubuko.com

leetcode--Plus One

标签:c   class   blog   code   java   a   

原文地址:http://www.cnblogs.com/averillzheng/p/3773936.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!