2016-01-15 152 views
0

我正在嘗試編寫一個乘以兩個整數字符串的代碼。我不太確定它出錯的地方......它適用於某些數字,但對其他人來說卻是可怕的錯誤。我並不是要求一個完整的解決方案,而只是一個暗示(我真的很感謝任何可能的幫助),我在哪裏犯這個明顯愚蠢的錯誤。提前致謝。使用大整數類的字符串乘法

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

什麼是錯誤,導致錯誤的輸入是什麼? – Leo

+0

產品通常以數量級錯誤結束,例如100 * 8給出80.它也給出了像302 * 51 = 15234的答案。 – garserdt216

+0

您是否調試過您的代碼? – Thomas

回答

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實際上是成倍增加。這應該給你一個清晰的提示。