66. Plus One

LeetCode 66. Plus One

Description

Given a non-empty array of decimal digits representing a non-negative integer, increment 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 contains a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Constraints:

  • 1 <= digits.length <= 100

  • 0 <= digits[i] <= 9

Tags

Math, Array

Solution

We initialize a variable c with 1 for the carry. Traverse the array from the right. We add c onto the current digit and reset c = 0 (IMPORTANT). Then we check if the current digit is larger than 9, if it is then update the carry and this digit in Add Two Numbers manner. After loop, we need to check if there is still a carry, if c ≠ 0, we need to append c in front of the digits.

Complexity

  • Time complexity: O(n)O(n)

  • Space complexity: O(n)O(n)

Code

func plusOne(digits []int) []int {
	c := 1
	for i := len(digits) - 1; i >= 0; i-- {
		digits[i] += c
		c = 0 // important
		if digits[i] > 9 {
			c = digits[i] / 10
			digits[i] %= 10
		}
	}
	if c != 0 {
		return append([]int{c}, digits...)
	}
	return digits
}

Last updated

Was this helpful?