AcWing 792. 高精度减法
原题链接
简单
作者:
温斯顿
,
2021-03-03 10:55:21
,
所有人可见
,
阅读 232
Java 代码
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String a = reader.readLine();
String b = reader.readLine();
List<Integer> diff = null;
boolean negative = false;
if (compare(a, b)) {
diff = substract(a, b);
} else {
negative = true;
diff = substract(b, a);
}
StringBuilder builder = new StringBuilder();
for (int i = diff.size() - 1; i >= 0; i--) {
if (diff.get(i) == 0 && builder.length() == 0) continue;
builder.append(diff.get(i));
}
if (builder.length() == 0) {
System.out.print(0);
} else if (negative) {
System.out.print('-');
System.out.print(builder.toString());
} else {
System.out.print(builder.toString());
}
}
public static boolean compare(String a, String b) {
if (a.length() != b.length()) return a.length() > b.length();
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) != b.charAt(i)) {
return a.charAt(i) > b.charAt(i);
}
}
return true;
}
public static List<Integer> substract(String a, String b) {
// a >= b
List<Integer> diff = new ArrayList<>();
int i = a.length() - 1;
int j = b.length() - 1;
int t = 0;
while (i >= 0) {
t = a.charAt(i--) - '0' - t;
t -= j >= 0 ? b.charAt(j--) - '0' : 0;
diff.add((t + 10) % 10);
t = t < 0 ? 1 : 0;
}
return diff;
}
}