[LeetCode]66、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.

思路:

大数存储,加一。一个整数,存在一个数组中,最高位在a[0],最低位在a[a.lenth-1].要在末尾+1,如果a[a.lenth-1]<9,则直接加一返回。

如果等于9,则该位置0,往前一位继续计算。如果最高位仍是9,加一位会导致进位,则变为0,新加一位置1。

 1 public class Solution66 {
 2     public int[] plusOne(int[] digits){
 3         for(int i = digits.length-1;i >= 0;--i){
 4             if(digits[i]<9){
 5                 ++digits[i];
 6                 return digits;
 7             }
 8             else if(digits[i]==9){
 9                 digits[i]=0;
10             }
11         }
12         int[] res = new int[digits.length+1];
13         res[0] = 1;
14         return res;
15     }
16     public static void main(String[] args) {
17         // TODO Auto-generated method stub
18         Solution66 solution66 = new Solution66();
19         int[] digits = {0};
20         int[] result;
21         result= solution66.plusOne(digits);
22         for(int i = 0; i< result.length;i++){
23             System.out.print(result[i]);
24         }
25     }
26     
27 }