-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode989_ArrayFormOfInteger.java
More file actions
79 lines (66 loc) · 1.91 KB
/
Copy pathleetcode989_ArrayFormOfInteger.java
File metadata and controls
79 lines (66 loc) · 1.91 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
74
75
76
77
78
79
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class leetcode989_ArrayFormOfInteger {
public List<Integer> addToArrayForm(int[] A, int K) {
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
Stack<Integer> temp = new Stack<>();
Stack<Integer> res = new Stack<>();
List<Integer> finalList = new ArrayList<>();
int carry=0, sum=0;
for(int num : A){
stack1.add(num);
}
while(K != 0){
temp.add(K%10);
K = K/10;
}
while(!temp.isEmpty()){
stack2.add(temp.pop());
}
while(!stack1.isEmpty() && !stack2.isEmpty()){
sum = stack1.pop() + stack2.pop();
if(carry >0)
sum = sum + carry;
res.add(sum%10);
if(sum /10 > 0)
carry = 1;
else
carry = 0;
}
while(!stack1.isEmpty()){
sum = stack1.pop();
if(carry > 0)
sum = sum + carry;
res.add(sum%10);
if(sum /10 > 0)
carry = 1;
else
carry = 0;
}
while(!stack2.isEmpty()){
sum = stack2.pop();
if(carry > 0)
sum = sum + carry;
res.add(sum%10);
if(sum /10 > 0)
carry = 1;
else
carry = 0;
}
if(carry > 0)
res.add(carry);
while(!res.isEmpty()){
finalList.add(res.pop());
}
return finalList;
}
public static void main(String[] args) {
leetcode989_ArrayFormOfInteger obj = new leetcode989_ArrayFormOfInteger();
int A[] = {2,1,5};
int K = 806;
List<Integer> res = obj.addToArrayForm(A,K);
System.out.println(res.toString());
}
}