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 len = digits.length; 6 digits[len - 1] += 1; 7 int carry = 0; 8 for(int i = len - 1; i >= 0; i --){ 9 digits[i] += carry; 10 carry = 0; 11 if(digits[i] >= 10){ 12 carry = digits[i] / 10; 13 digits[i] %= 10; 14 } 15 } 16 if(carry > 0){ 17 int[] result = new int[len + 1]; 18 result[0] = carry; 19 for(int i = 0; i < len; i++){ 20 result[i + 1] = digits[i]; 21 } 22 return result; 23 } else { 24 return digits; 25 } 26 } 27 }
carry加完后需重置为0,因为后面只会有进位的时候才会重新计算carry