使用大整数 class 的字符串乘法

string multiplication using a big integer class

我正在尝试编写一个将两个整数字符串相乘的代码。我不太确定哪里出了问题......它适用于某些数字,但对其他人来说是非常错误的。我不是在寻求一个完整的解决方案,而只是一个提示(我非常感谢任何可能的帮助)关于我在哪里犯了明显愚蠢的错误。提前致谢。

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.print("Please enter a big integer. ");
    String t = scan.nextLine();
    System.out.print("And another. ");
    String s = scan.nextLine();

    BigInt a = new BigInt(t);
    BigInt b = new BigInt(s);

    System.out.println(a + " + " + b + " = " + a.add(b));
    System.out.println(a + " - " + b + " = " + a.sub(b));
    System.out.println(a + " * " + b + " = " + a.mul(b));
    System.out.println(a + " / " + b + " = " + a.div(b));
}
}

class BigInt {

public BigInt() {

    n = new int[1];
}

public BigInt(String s) {

    n = new int[s.length()];

    for (int i = 0; i < n.length; ++i) {
        n[n.length - i - 1] = s.charAt(i) - '0' ;
    }



}

private BigInt(int[] n) {

    this.n = new int[n.length];

    for (int i = 0; i < n.length; ++i) {
        this.n[i] = n[i];
    }
}

public String toString() {

    String s = "";

    for (int i : n) {
        s = i + s;
    }

    return s;
}

public BigInt mul(BigInt o) {

        int carry = 0;
        int s = 0;
        int digit;
        int subtotal = 0;
        int total = 0;

        int max = n.length > o.n.length ? n.length : o.n.length;
        int[] result = new int[n.length + o.n.length];

      for (int i = 0; i < o.n.length; ++i) {

        int bottom = i <= o.n.length ? o.n[i] : 0;

        for (s = 0; s <= n.length; ++s){

          int top = s < n.length ? n[s] : 0;
          int prod = (top * bottom + carry);

          if (s == (max-1)) {

            total = Integer.valueOf((String.valueOf(prod) + String.valueOf(subtotal)));
            carry = 0;
            digit = 0;
            subtotal = 0;
            break;
          }

          if (prod < 10) {

            digit = prod;
            subtotal += digit;
            carry = 0;
          }

          if (prod >= 10); {

            digit = prod % 10;
            carry = prod / 10;
            subtotal += digit;
          }
        }
        result[i] = total;
      }
    return new BigInt(trim(result));
}

private int[] trim(int[] nums) {

    int size = nums.length;

    for (int i = nums.length - 1; i > 0; --i) {
        if (nums[i] != 0) {
            break;
        }
        --size;
    }

    int[] res = new int[size];

    for (int i = 0; i < size; ++i) {
        res[i] = nums[i];
    }

    return res;
}

private int[] n;
}

快速测试使用:

    for (int x = 0; x < 10; x++) {
        for (int y = 0; y < 10; y++) {
            System.out.println(x + " * " + y + " = " + new BigInt(Integer.toString(x)).mul(new BigInt(Integer.toString(y))));

        }
    }

表明 x * y 的乘积实际上是 10x * y 的乘积。那应该给你一个明确的问题提示。