1. Question
给定一个非负数,用数组存储其各数位,对这个数加一,返回结果。数组中,最高位在数组头。
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.
2. Solution
public class Solution {public int[] plusOne( int[] digits ){digits[digits.length-1]++;int i;for( i=digits.length-1; i>0 && digits[i]/10 != 0; i-- ){digits[i-1] += digits[i]/10;digits[i] = digits[i] % 10;}int[] res = null;int k; //the start point of res to copy from digitsif( digits[i]/10!=0 ){res = new int[ digits.length + 1 ];res[0] = digits[i] / 10;digits[i] = digits[i] % 10;k = 1;}else{res = new int[ digits.length ];k = 0;}System.arraycopy(digits, 0, res, k, digits.length);return res;}
}