AcWing792高精度减法
题目:
题目大意:
模拟大数字减法。
数据范围:
如图所示
思路:
模拟。先判断哪个数字大,用大的数numa减去较小的数numb,最后添加“-”(如果是小的数减去较大的数的话),从低位开始依次减,初始设置借位 t 为 0 ,t = numa[i] - t, 如果i没有越过numb的界,则t -= numb[i],则计算出该位为(t + 10)% 10,将其加入numc中。如果t为负数,则说明该位向高位借位了,则设置t为1,以便下一次运算中高位减去借的位。
注意:可能产生许多前导零,最后应除去。
代码:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static boolean cmp(List<Integer> numa, List<Integer> numb){
if (numa.size() > numb.size())
return true;
else if (numa.size() < numb.size())
return false;
else {
for (int i = numa.size() - 1; i >= 0; i -- ){
if (numa.get(i) == numb.get(i))
continue;
else if (numa.get(i) > numb.get(i))
return true;
else
return false;
}
}
return true;
}
public static List<Integer> sub(List<Integer> numa, List<Integer> numb){
List<Integer> numc = new ArrayList<>();
int t = 0;
for (int i = 0; i < numa.size(); i ++ ){
t = numa.get(i) - t;
if (i < numb.size()){
t -= numb.get(i);
}
numc.add((t + 10) % 10);
if (t < 0)
t = 1;
else
t = 0;
}
for (int i = numc.size() - 1; i >= 1; i -- ){
if (numc.get(i) != 0)
break;
else
numc.remove(i);
}
return numc;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.next(), b = scanner.next();
List<Integer> numa = new ArrayList<>(), numb = new ArrayList<>();
for (int i = a.length() - 1; i >= 0; i -- ){
numa.add(a.charAt(i) - '0');
}
for (int i = b.length() - 1; i >= 0; i -- ){
numb.add(b.charAt(i) - '0');
}
if (cmp(numa, numb)){
List<Integer> numc = sub(numa, numb);
for (int i = numc.size() - 1; i >= 0; i -- ){
System.out.print(numc.get(i));
}
}else {
List<Integer> numc = sub(numb, numa);
System.out.print("-");
for (int i = numc.size() - 1; i >= 0; i -- ){
System.out.print(numc.get(i));
}
}
}
}
时空复杂度分析等:
-
时间复杂度 : O(n)
-
空间复杂度 : O(n)