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.
_*Example_8
Given [1,2,3] which represents 123, return [1,2,4].
Given [9,9,9] which represents 999, return [1,0,0,0].
Tags
Array Google
Related Problems
Medium Divide Two Integers 15 %
Easy Add Binary
Analysis
比较巧的方法是将 +1 当做末位digit的进位carries;每次进位 carries = sum / 10;,留下的数字为 digits[i] = sum % 10;
如果最终进位 != 0,说明要新增加一位,则新建数组把计算结果填进去。
Solution
publicclassSolution { /** * @param digits a number represented as an array of digits * @return the result */publicint[] plusOne(int[] digits) {int carries =1;for (int i =digits.length-1; i >=0&& carries >0; i--) {int sum = digits[i] + carries; digits[i] = sum %10; carries = sum /10; }if (carries ==0) {return digits; }int[] result =newint[digits.length+1]; result[0] =1;for (int i =1; i <result.length; i++) { result[i] = digits[i -1]; }return result; }}