LeetCode----66. Plus One(Java)

 1 package plusOne66;
 2 /*
 3     Given a non-negative number represented as an array of digits, plus one to the number.
 4     The digits are stored such that the most significant digit is at the head of the list. 
 5  */
 6 public class Solution {
 7 
 8     public static int[] plusOne(int[] digits) {
 9         int index=digits.length-1;
10         digits[index]=digits[index]+1;
11         while(digits[index]>=10&&index>0){
12             digits[index]=digits[index]%10;
13             index--;
14             digits[index]=digits[index]+1;
15         }
16         if (digits[0]>9)
17         {
18             digits[0]=digits[0]%10;
19             int[] result=new int[digits.length+1];
20             result[0]=1;
21             for (int i=0;i<digits.length;i++){
22                 result[i+1]=digits[i];
23             }
24             return result;
25         }
26         return digits;
27     }
28     public static void main(String[] args) {
29         // TODO Auto-generated method stub
30 
31         int[] digits={9,9,9,9};
32         //System.out.println(plusOne(digits).toString());
33     }
34 
35 }

 

posted @ 2016-09-13 21:29  蒲公英的花朵  阅读(207)  评论(0)    收藏  举报