-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDifferenceOfTwoArrays.java
74 lines (62 loc) · 2.12 KB
/
DifferenceOfTwoArrays.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
65
66
67
68
69
70
71
72
73
74
import java.util.Scanner;
public class DifferenceOfTwoArrays{
public static void main(String[] args) throws Exception{
Scanner scn = new Scanner(System.in);
// input 1st array and its elements
System.out.print("enter the size of 1st array: ");
int n1 = scn.nextInt();
System.out.println("enter the value in the 1st array: ");
int[] arr1 = new int[n1];
for(int i=0; i<arr1.length; i++){
arr1[i] = scn.nextInt();
}
// intput second array and its elements
System.out.print("enter the size of 2nd array: ");
int n2 = scn.nextInt();
System.out.println("(bigger than first array)");
System.out.println("enter the value in the 2nd array: ");
int[] arr2 = new int[n2];
for(int i=0; i<arr2.length; i++){
arr2[i] = scn.nextInt();
}
// 3rd array to store result of the substraction
int[] arrS = new int[n2]; // n2 will be greater than n1 acc to quesiton
// substraction of two array
int i = arr1.length - 1;
int j = arr2.length - 1;
int k = arrS.length - 1;
int carry = 0;
while(k >= 0){
int ans = 0;
// after reaching zero of smaller array assign all other value less than 0 as 0
int arrr1val = i >= 0 ? arr1[i] : 0;
if(arr2[j] + carry >= arrr1val){
ans = arr2[j] + carry - arrr1val;
carry = 0;
}
else{
ans = (arr2[j] + carry + 10) - arrr1val;
carry = -1;
}
arrS[k] = ans;
i--;
j--;
k--;
}
// ignore printing preceeding zeros in the output
int index = 0;
while(index < arrS.length){
if(arrS[i] == 0){
index++;
}
else{
break;
}
}
System.out.println("answer is: ");
while(index < arrS.length){
System.out.println(arrS[index]);
index++;
}
}
}