66. Plus One #
Problem #
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Problem Summary #
Given a non-empty array composed of integers representing a non-negative integer, add one to the number. The most significant digit is stored at the first position of the array, and each element in the array stores only a single digit. You may assume that except for the integer 0, this integer will not start with zero.
Solution Approach #
- Given an array representing a decimal number, where index 0 of the array is the high-order digit of the decimal number. Compute the result after adding one to this decimal number.
- A simple simulation problem. Start scanning from the end of the array toward the front, carrying digit by digit. If there is still a carry at the highest digit, insert another 1 at position 0 in the array.
Code #
package leetcode
func plusOne(digits []int) []int {
for i := len(digits) - 1; i >= 0; i-- {
digits[i]++
if digits[i] != 10 {
// no carry
return digits
}
// carry
digits[i] = 0
}
// all carry
digits[0] = 1
digits = append(digits, 0)
return digits
}