-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAddNumbers.java
More file actions
73 lines (63 loc) · 1.82 KB
/
AddNumbers.java
File metadata and controls
73 lines (63 loc) · 1.82 KB
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
//Add two numbers represented by two arrays A & B and return the resulting sum in Array.
import java.util.*;
class AddNumbers{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
List<Integer> A = new ArrayList<>();
List<Integer> B = new ArrayList<>();
for (int i = 0; i < n; i++) {
A.add(sc.nextInt());
}
for (int i = 0; i < m; i++) {
B.add(sc.nextInt());
}
List<Integer> result = addNumbers(n, m, A, B);
for (Integer x : result) {
System.out.print(x);
}
}
static List<Integer> addNumbers(int n, int m, List<Integer> A,
List<Integer> B){
List<Integer> ans = new ArrayList<Integer>();
/* String Astr="";
String Bstr="";
for(int i =0 ; i<A.size(); i++){
Astr = Astr + ""+A.get(i);
}
for(int i =0 ; i<B.size(); i++){
Bstr = Bstr + ""+B.get(i);
}
int result = Integer.parseInt(Astr) + Integer.parseInt(Bstr);
ans.add(result); */
if(A.size() > B.size()){
fillZeros(A, B);
}else if(B.size() > A.size()){
fillZeros(B,A);
}
int max = A.size();
int carry=0;
for(int i=A.size()-1; i>=0; i--){
int sum = (A.get(i) + B.get(i) + carry ) % 10;
ans.add(sum);
if((A.get(i) + B.get(i) + carry) >= 10){
carry = 1;
}else{
carry = 0;
}
}
if(carry == 1) ans.add(carry);
Collections.reverse(ans);
return ans;
}
public static List<Integer> fillZeros(List<Integer> mylist1,List<Integer> mylist2){
int diff = mylist1.size() - mylist2.size();
int i = 0;
while(i!=diff){
mylist2.add(i,0);
i++;
}
return mylist2;
}
}