Problem:
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
Given [1,2,3] which represents 123, return [1,2,4].
Given [9,9,9] which represents 999, return [1,0,0,0].
Leetcode link
Lintcode link
Solution:
It is a essay problem, just add carry though the list, until the carry equals 0.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| > File Name: PlusOne.java > Author: Yao Zhang > Mail: psyyz10@163.com > Created Time: Fri 13 Nov 14:27:19 2015 ************************************************************************/ public class PlusOne{ public int[] plusOne(int[] digits){ int carry = 1; for (int i = digits.length - 1; i >= 0 && carry > 0; i--){ int sum = digits[i] + carry; carry = sum / 10; digits[i] = sum % 10; } if (carry == 0) return digits; int[] newDigits = new int[digits.length + 1]; newDigits[0] = carry; for (int i = 1; i < newDigits.length; i++){ newDigits[i] = digits[i - 1]; } return newDigits; } }
|