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

时间:2016-01-15 12:23:39

标签: java string multiplication

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

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;
}

1 个答案:

答案 0 :(得分:0)

使用以下方法进行快速测试:

    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。这应该会给你一个明确的暗示。