Plus One

Plus One 

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 public class Solution {
 2     public int[] plusOne(int[] digits) {
 3             digits[digits.length - 1] += 1;
 4             for(int i = digits.length - 1; i >=0 ; i--){
 5                 if((digits[i] / 10) == 1 && i != 0){//有进位
 6                     digits[i] = digits[i] % 10;
 7                     digits[i - 1] += 1;//向高位进1
 8                 }
 9             }
10             if(digits[0] / 10 == 0)
11                 return digits;
12             else{
13                 int result[] = new int[digits.length + 1];
14                 System.arraycopy(digits, 0, result, 1, digits.length);
15                 result[0] = 1;
16                 result[1] %= 10;
17                 return result;
18             }
19        }
20 }

 

posted on 2014-11-10 20:55  luckygxf  阅读(181)  评论(0编辑  收藏  举报

导航