先贴上代码
1 public String multiply(String num1, String num2) { 2 String str = ""; 3 StringBuffer sb = new StringBuffer(num1); 4 num1 = sb.reverse().toString(); 5 sb = new StringBuffer(num2); 6 num2 = sb.reverse().toString(); 7 int[] res = new int[num1.length() + num2.length()]; 8 for (int i = 0; i < num1.length(); i++) { 9 for (int j = 0; j < num2.length(); j++) { 10 res[i + j] += (num1.charAt(i) - ‘0‘) * (num2.charAt(j) - ‘0‘); 11 } 12 } 13 int k = 0, contribute = 0; 14 while (k < res.length || contribute > 0) { 15 int tmp = k<res.length?res[k]:0; 16 tmp = contribute+tmp; 17 contribute = tmp/10; 18 str += tmp%10; 19 k++; 20 } 21 sb = new StringBuffer(str); 22 str = sb.reverse().toString(); 23 int i = 0; 24 while(i<str.length()&&str.charAt(i)==‘0‘) 25 i++; 26 if(i<str.length()){ 27 str = str.substring(i); 28 }else{ 29 str = "0"; 30 } 31 return str; 32 }
思路如下:
模拟竖式相乘
1、转换并反转,字序反转;
2、逐位相乘,结果存放在res[i+j]中;
3、处理进位;
4、转换并反转,将计算结果转换为字符串并反转。
5、消除多余的0;
两数相乘,结果的长度一定不大于乘数和被乘数的长度之和。
上述也可以用直接用java的BigInteger类实现
public static void main(String[] args) { String a = "98989898989898956898", b = "989892551548781251323265615150"; BigInteger aa = new BigInteger(a); BigInteger bb = new BigInteger(b); System.out.println(aa.multiply(bb)); }
时间: 2024-11-07 05:31:26