AcWing 792. 高精度减法
原题链接
简单
作者:
蜗牛爱吃草
,
2019-12-18 20:44:37
,
所有人可见
,
阅读 743
java 代码
import java.io.*;
import java.util.*;
class Main{
public static void main(String[] args) throws Exception{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));//读取系统的输入
String[] num1 = reader.readLine().split(" ");
String[] num2 = reader.readLine().split(" ");
List<Integer> a = new ArrayList<>();
List<Integer> b = new ArrayList<>();
String as = num1[0];
String bs = num2[0];
for(int i = 0;i < num1[0].length();i++){
a.add(as.charAt(i) - '0');
}
for(int i = 0;i < bs.length();i++){
b.add(bs.charAt(i) - '0');
}
if(a.size() < b.size()){
System.out.println("-"+SUB(a,b));
}else if(a.size() == b.size()){
if(a.get(0) < b.get(0)){
System.out.println("-"+SUB(a,b));
}else{
System.out.println(SUB(a,b));
}
}else{
System.out.println(SUB(a,b));
}
}
public static String SUB(List<Integer> a, List<Integer> b){
if(a.size() < b.size()) return SUB(b,a);
else if(a.size() == b.size()){
if(a.get(0) < b.get(0)){
return SUB(b,a);
}
}
StringBuilder sb = new StringBuilder();
int tmp = 0;
int sub = 0;
while(!b.isEmpty()){
int sub1 = a.remove(a.size() - 1) - sub;
int sub2 = b.remove(b.size() - 1);
if(sub1 >= sub2){
tmp = sub1 - sub2;
sub = 0;
}else{
tmp = sub1 + 10 - sub2;
sub = 1;
}
sb.append(tmp);
}
while(!a.isEmpty()){
int su = a.remove(a.size() - 1) - sub;
if(su < 0){
su = su + 10;
sub = 1;
}else{
sub = 0;
}
sb.append(su);
}
while(sb.length() > 0 && sb.charAt(sb.length() - 1) == '0'){
sb.deleteCharAt(sb.length() - 1);
}
if(sb.length() == 0) return "0";
return sb.reverse().toString();
}
}