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.
这道题的要求是给定一个数组表示非负整数,其高位在数组的前面,对这个整数加1。
思路:和加法一样,从后往前遍历,若该位元素<9,则加一,若该位元素为9,则加一后该位元素为0。若数组中元素全是9,则结果比原数组长度大一,第一个元素为1,其余均为0。
1 public int[] plusOne(int[] digits) { 2 int carry =1; 3 for (int i=digits.length-1;i>=0;i--) 4 { 5 int sum = carry + digits[i]; 6 digits[i] = sum%10; 7 carry = sum/10; 8 } 9 if (carry ==0) return digits; 10 int[] result = new int[digits.length+1]; 11 result[0] = carry; 12 for (int i=0;i<digits.length;i++) 13 { 14 result[i+1] = digits[i]; 15 } 16 return result; 17 }