Skip to content

Array Sum

Problem Description

You are given two numbers represented as integer arrays A and B, where each digit is an element.

You have to return an array which representing the sum of the two given numbers.

The last element denotes the least significant bit, and the first element denotes the most significant bit.

Problem Constraints

1 <= |A|, |B| <= 105
0 <= Ai, Bi <= 9

Input Format The first argument is an integer array A. The second argument is an integer array B.

Output Format Return an array denoting the sum of the two numbers.

Example Input

Input 1:
A = [1, 2, 3]
B = [2, 5, 5]

Input 2:
A = [9, 9, 1]
B = [1, 2, 1]

Example Output

Output 1:
[3, 7, 8]

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

Example Explanation

Explanation 1:
Simply, add all the digits in their place.

Explanation 2:
991 + 121 = 1112
Note that the resultant array size might be larger.

Solution

swift
import Foundation

class Solution {
	func addArrays(_ A: inout [Int], _ B: inout [Int]) -> [Int] {
        var result = [Int](repeating:0,count:max(A.count,B.count)+1)
        
        var lenA = A.count
        var lenB = B.count
        var lenC = result.count
        
        var carry = 0
        for i in 0..<min(A.count,B.count)
        {
            let sum =  A[lenA-1-i] + B[lenB-1-i] + carry
            result[lenC-1-i] = sum%10
            carry = sum/10            
        }
        var len = 0
        if A.count < B.count {
            for i in A.count..<B.count {
                let sum = B[lenB - 1 - i] + carry
                result[lenC-1-i] = sum%10
                carry = sum/10 
            }
            len = B.count
            
        } else if A.count > B.count {
            for i in B.count..<A.count {
                let sum = A[lenA - 1 - i] + carry
                result[lenC-1-i] = sum%10
                carry = sum/10 
            } 
            len = A.count
        } else {
            len = A.count
        }
        
        
        if carry > 0 {
            result[result.count - 1 - len] = carry
            return Array(result[(result.count - len - 1)..<result.count])
        } else {
            return Array(result[(result.count - len)..<result.count])
        }   
	}
}

Reference