703046. Sum of two numbers represented as arrays
Sum of two numbers represented as arrays
Slug: sum-of-two-numbers-represented-as-arrays3110
Difficulty: Easy
Id: 703046
Topic Tags: Arrays, Data Structures
Company Tags: Zoho, Accolite, Amazon
Summary
Given two integer arrays arr1 and arr2, each representing a number in base 10, find the sum of these numbers. The input arrays are guaranteed to be valid representations of non-negative integers.
The key concepts involved in this problem are arrays and data structures.
Detailed Explanation
To solve this problem, we can convert the two arrays into integers and then add them together. We can use a simple loop to iterate over the arrays, multiplying each digit by its corresponding power of 10 (since we're working with base 10) and adding it to our running total.
Here's a step-by-step breakdown of the solution:
- Initialize an integer
resultto 0. - Iterate over the lengths of both input arrays using a for loop. Let's call these lengths
n1andn2. - For each iteration, multiply the current digit of
arr1by 10^(n2-1) (since we're subtracting one from n2 because array indices start at 0). - Add this product to
result. - Repeat steps 2-4 for
arr2, multiplying each digit by 10^(n1-1). - Return the sum of
resultand the result of addingarr1[0]andarr2[0].
Here's an ASCII art diagram illustrating this process:
arr1: [1, 2, 3]
arr2: [4, 5]
Initialize result = 0
Iterate over lengths:
n1 = 3, n2 = 2
Multiply current digit of arr1 by 10^(n2-1) = 10^1 = 10
Add product to result = 0 + 10 = 10
Repeat for arr2: multiply each digit by 10^(n1-1) = 10^2 = 100
Add products to result = 10 + 100 = 110
Return sum of result and first digits: 110 + (1+4) = 115
The time complexity for this solution is O(n1+n2), where n1 and n2 are the lengths of the input arrays. The space complexity is O(1), since we only use a constant amount of extra memory.
Optimized Solutions
Java
public int sumOfArrays(int[] arr1, int[] arr2) {
int result = 0;
for (int i = Math.max(arr1.length - 1, arr2.length - 1); i >= 0; i--) {
result += (arr1[i] + arr2[i]) * (int)Math.pow(10, i);
}
return result;
}