703040. Add two numbers represented by two arrays
Easy
Add Two Numbers Represented by Two Arrays
Summary
Given two arrays representing numbers in base 10, write a program to add these two numbers. For example, given two arrays [1,2,3] and [4,5], the sum should be [5,7,8].
Detailed Explanation
The problem involves adding two numbers represented as arrays of digits. We can solve this problem by treating each array as a number in base 10, then performing addition.
Here's a step-by-step breakdown:
- Initialize an empty result array.
- Iterate through the two input arrays from right to left (i.e., from least significant digit to most).
- For each pair of digits, add them together and store the result modulo 10 in the corresponding position of the result array.
- If the sum is greater than or equal to 10, append the carry (the quotient when dividing the sum by 10) to the front of the result array.
- Repeat steps 2-4 until all pairs of digits have been processed.
Time complexity: O(n), where n is the length of the longer input array. Space complexity: O(n), as we need to store the result in an array of size n.
Optimized Solutions
Java
java
public int[] addArrays(int[] arr1, int[] arr2) {
int maxLen = Math.max(arr1.length, arr2.length);
int[] res = new int[maxLen];
for (int i = 0; i < maxLen; i++) {
int sum = (i < arr1.length ? arr1[i] : 0) + (i < arr2.length ? arr2[i] : 0);
res[i] = sum % 10;
if (sum >= 10) {
res[0] = (res[0] == 0) ? 1 : res[0];
}
}
return res;
}
Python
python
def add_arrays(arr1, arr2):
max_len = max(len(arr1), len(arr2))
res = [0] * max_len
for i in range(max_len):
sum = (i < len(arr1) and arr1[i] or 0) + (i < len(arr2) and arr2[i] or 0)
res[i] = sum % 10
if sum >= 10:
res[0] += 1
return res
C++
Not available