Skip to content

Adding one to number represented as array of digits

Problem Description

Given a non-negative number represented as an array of digits, add 1 to the number ( increment the number represented by the digits ).

The digits are stored such that the most significant digit is at the head of the list.

Problem Constraints

1 <= |A| <= 106
0 <= Ai <= 9
1 <= |A| <= 106
0 <= Ai <= 9

Input Format

First argument is an array of digits.
First argument is an array of digits.

Output Format

Return the array of digits after adding one.
Return the array of digits after adding one.

Example Input

Input 1:
[1, 2, 3]
Input 1:
[1, 2, 3]

Example Output

Output 1:
[1, 2, 4]
Output 1:
[1, 2, 4]

Example Explanation

Explanation 1:

Given vector is [1, 2, 3].
The returned vector should be [1, 2, 4] as 123 + 1 = 124.
Explanation 1:

Given vector is [1, 2, 3].
The returned vector should be [1, 2, 4] as 123 + 1 = 124.

TIP

Certain things are intentionally left unclear in this question which you should practice asking the interviewer.

For example: for this problem, following are some good questions to ask :

  • Q : Can the input have 0's before the most significant digit. Or in other words, is 0 1 2 3 a valid input? (YES)
  • Q : Can the output have 0's before the most significant digit? Or in other words, is 0 1 2 4 a valid output? (NO)

Solution

TIP

Array Iteration.

swift
import Foundation

class Solution {
	func plusOne(_ A: inout [Int]) -> [Int] {
        let len = A.count
        var result = [0] + A 
        var i = len
        
        while i >= 0 {
            result[i] += 1
            if result[i] < 10 {
                break
            }
            result[i] = 0
            
            i -= 1
        }
        
        i = 0
        while i <= len {
            if result[i] > 0 {
                break
            }
            i += 1
        }
        
        return Array(result[i...len])        
	}
}
import Foundation

class Solution {
	func plusOne(_ A: inout [Int]) -> [Int] {
        let len = A.count
        var result = [0] + A 
        var i = len
        
        while i >= 0 {
            result[i] += 1
            if result[i] < 10 {
                break
            }
            result[i] = 0
            
            i -= 1
        }
        
        i = 0
        while i <= len {
            if result[i] > 0 {
                break
            }
            i += 1
        }
        
        return Array(result[i...len])        
	}
}

Reference