精度加减(大数加法和减法的实现)

2021-01-14  本文已影响0人  Wilbur_

听起来好像是个编程语言都应该自带的功能,但是通过在编程语言里实现加法和减法会让别人看到你是否了解计算机的原理
这个通常是很多面试的基础问题,然后通过这个之后在深入。属于热身类型的题目。下面是实现它们的代码
加法:

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String n1 = br.readLine();
        String n2 = br.readLine();
        int[] num1 = new int[n1.length()];
        int[] num2 = new int[n2.length()];
        int idx = 0;
        for (int i = n1.length() - 1; i >= 0; i--) num1[idx++] = n1.charAt(i) - '0';
        idx = 0;
        for (int i = n2.length() - 1; i >= 0; i--) num2[idx++] = n2.charAt(i) - '0';
        int[] res = add(num1, num2);
        // System.out.print(Arrays.toString(res));
        if (res[res.length - 1] != 0) {System.out.print(res[res.length-1]);}
        for (int i = res.length - 2; i >= 0; i--) {
            System.out.print(res[i]);
        }
    }
    static int[] add(int[] n1, int[] n2) {
        int maxLength = Math.max(n1.length, n2.length) + 1;
        int[] res = new int[maxLength];
        int sum = 0;
        for (int i = 0; i < n1.length || i < n2.length; i++) {
            if (i < n1.length) sum += n1[i];
            if (i < n2.length) sum += n2[i];
            res[i] = sum % 10;
            sum /= 10;
        }
        if (sum != 0) {
            res[maxLength - 1] = sum;
        }
        return res;
    }
}
上一篇下一篇

猜你喜欢

热点阅读