algo. quick_sort

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
import java.util.*;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str1 = sc.next();
String str2 = sc.next();
List<Integer> num1 = new ArrayList<>(str1.length());
List<Integer> num2 = new ArrayList<>(str2.length());

for (int i = 0; i < str1.length(); i++) {
num1.add(str1.charAt(str1.length() - 1 - i) - '0');
}
for (int i = 0; i < str2.length(); i++) {
num2.add(i, str2.charAt(str2.length() - 1 - i) - '0');
}

if (cmp(num1, num2)) {
List<Integer> res = sub(num1, num2);
if (res.size() == 0) {
System.out.print('0');
return;
}
for (int i = res.size() - 1; i >= 0; i--) {
System.out.print(res.get(i));
}
}
else {
List<Integer> res = sub(num2, num1);
System.out.print('-');
for (int i = res.size() - 1; i >= 0; i--) {
System.out.print(res.get(i));
}
}

}

// compare two numbers
public static boolean cmp(List<Integer> num1, List<Integer> num2) {
if (num1.size() > num2.size()) return true;
else if (num1.size() < num2.size()) return false;
else {
int i = num1.size() - 1;
while (num1.get(i) == num2.get(i) && i > 0) {
i--;
}
return num1.get(i) >= num2.get(i);
}
}

public static List<Integer> sub(List<Integer> num1, List<Integer> num2) {
int t = 0;
List<Integer> res = new ArrayList(num1.size());
for (int i = 0; i < num1.size(); i++) {
int a = num1.get(i) - t, b = i < num2.size() ? num2.get(i) : 0;
if (a >= b) {
res.add(a - b);
t = 0;
}
else {
res.add(a + 10 - b);
t = 1;
}
}

int end = res.size() - 1;
while (end >= 0 && res.get(end) == 0) {
end--;
}

return res.subList(0, end + 1);
}
}

algo. quick_sort
http://elwinliu.com/2024/09/08/algo. integer_sub/
Author
Elwin
Posted on
September 8, 2024
Licensed under