LeetCode 66. Plus One

原题链接在这里:https://leetcode.com/problems/plus-one/

题目:

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

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

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

题解:

特殊情况是 全是9时需要新建一个数组。

Time Complexity: O(n). Space: O(n).

AC Java:

 1 public class Solution {
 2     public int[] plusOne(int[] digits) {
 3         if(digits == null || digits.length == 0){
 4             return digits;
 5         }
 6         int carry = 1;
 7         for(int i = digits.length-1; i>=0; i--){
 8             int cur = (digits[i]+carry)%10;
 9             carry = (digits[i]+carry)/10;
10             digits[i] = cur;
11             
12             if(carry == 0){
13                 return digits;
14             }
15         }
16         
17         int [] res = new int[digits.length+1];
18         res[0] = 1;
19         return res;
20     }
21 }

跟上Add Binary.

posted @ 2015-12-05 05:09  Dylan_Java_NYC  阅读(363)  评论(0编辑  收藏  举报