Plus One

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

 1 public class Solution {
 2     public int[] plusOne(int[] digits) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         int carry = 0;
 6         boolean sig = false;
 7         int[] result = null;
 8         if(digits == null) return null;
 9         for(int i = 0;i < digits.length; i ++){
10             if(digits[i] != 9) sig = true;
11         }
12         if(sig == false){
13             result = new int[digits.length + 1];
14             result[0] = 1;
15             return result;
16         }else{
17             result = new int[digits.length];
18             result[digits.length - 1] = digits[digits.length - 1] + 1;
19             if(result[digits.length - 1] > 9){
20                 result[digits.length - 1] -= 10;
21                 carry = 1;
22             }
23             for(int i = digits.length - 2; i > -1; i --){
24                 result[i] = digits[i] + carry;
25                 if(result[i] > 9){
26                     result[i] -= 10;
27                     carry = 1;
28                 }else{
29                     carry = 0;
30                 }
31             }
32             return result;
33         }
34     }
35 }

 Second Round:

 1 public class Solution {
 2     public int[] plusOne(int[] digits) {
 3         boolean sig = false;
 4         for(int i = 0; i < digits.length; i ++)
 5             if(digits[i] != 9) sig = true;
 6         if(!sig){
 7             int[] result = new int[digits.length + 1];
 8             result[0] = 1;
 9             return result;
10         }
11         int[] result = new int[digits.length];
12         int carry = 1;
13         for(int i = digits.length - 1; i > -1; i --){
14             result[i] = (digits[i] + carry) % 10;
15             carry = (digits[i] + carry) / 10;
16         }
17         return result;
18     }
19 }

 

posted on 2013-10-02 07:13  Step-BY-Step  阅读(203)  评论(0编辑  收藏  举报

导航