-
Notifications
You must be signed in to change notification settings - Fork 1
/
SumOfTwoArrays.java
64 lines (49 loc) · 1.4 KB
/
SumOfTwoArrays.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main.com.sumit.coding.topics.arrays;
import java.util.Arrays;
/*
* Sum Of Two Arrays
* Problem URL : https://www.codingninjas.com/codestudio/problems/sum-of-two-arrays_893186
* */
public class SumOfTwoArrays {
public static void main(String[] args) {
int[] a = {9, 9, 9};
int[] b = {9, 9, 9};
System.out.println(Arrays.toString(findArraySum(a, a.length, b, b.length)));
}
/*
* Time Complexity : O(n)
* */
public static int[] findArraySum(int[] a, int n, int[] b, int m) {
int i = n - 1;
int j = m - 1;
int len = m;
if (n != m) len = Math.max(m, n);
else if (a[0] + b[0] > 9) len = m + 1;
int[] result = new int[len];
int k = len - 1;
int carry = 0;
while (i >= 0 && j >= 0) {
int val1 = a[i--];
int val2 = b[j--];
int sum = val1 + val2 + carry;
carry = sum / 10;
sum %= 10;
result[k--] = sum;
}
while (i >= 0) {
int sum = a[i--] + carry;
carry = sum / 10;
sum %= 10;
result[k--] = sum;
}
while (j >= 0) {
int sum = b[j--] + carry;
carry = sum / 10;
sum %= 10;
result[k--] = sum;
}
if (carry != 0 && k >= 0)
result[k--] = carry;
return result;
}
}