AcWing 792. 高精度减法-Java数组
原题链接
简单
作者:
装酷的小胖子
,
2021-04-01 16:49:39
,
所有人可见
,
阅读 376
Java 代码
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import static java.lang.System.*;
public class Main{
public static int cmp(int[] a, int[] b){
if(a.length > b.length) return 1;
if(a.length < b.length) return -1;
for(int i = a.length -1; i>=0; i--){
if(a[i] > b[i]) return 1;
else if (a[i] < b[i]) return -1;
}
return 0;
}
public static void main(String[] agrs) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String m = br.readLine(), n = br.readLine();
int al = m.length(), bl = n.length(), len = Math.max(al, bl);
int[] a = new int[al];
int[] b = new int[bl];
int[] c = new int[len];
for(int i = al -1, j = 0; i >= 0; i--,j++) a[j] = m.charAt(i) - '0';
for(int i = bl -1, j = 0; i >= 0; i--,j++) b[j] = n.charAt(i) - '0';
int p = cmp(a,b);
if( p == -1){
int[] tmp = b;
b = a;
a = tmp;
}else if(p == 0){
out.print('0');
return;
}
for(int i = 0, t = 0; i < len; i++, t = t < 0 ? 1 : 0){
t = a[i] - t;
if( i < b.length) t -= b[i];
c[i] = (t + 10) % 10;
}
//排除多余的0
while(--len > 0 && c[len] == 0);
if(p == -1) out.print('-');
for(int i = len; i >= 0; i--) out.print(c[i]);
}
}