66_Plus One

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.

Example

Input: [1,2,3,4] representing number 1234
Output: [1,2,3,5] representing number 1235

Input: [1,2,3,9] representing number 1239
Output: [1,2,4,0] representing number 1240

Input: [9,9,9,9] representing number 9999
Output: [1,0,0,0,0] representing number 10000

Solution 1: brute force

  • Start with the rightmost digit and work to the left, and specify carry value for each move

  • If the sum is 10, replace the digit with 0, and set carry be 1

  • If the sum less than 10, add current carry to the digit, and set carry be 0

  • After looping all digits, if carry = 1, add 1 at the beginning of digits

  • time complexity: O(n)O(n)

Solution 2: advanced

A fact to notice is when carry = 0, it will stay at 0 always. All the digits on the left of that element keeps the same.

Solution 3: convert the list to integer

  • Convert list to integer

  • Plus one to the integer

  • Convert back to a list

Note: this method might cause a overflow problem, i.e. if the integer is too large to store, it will cause an error.

Last updated

Was this helpful?