求解大数相乘问题
按照上图所示,进行嵌套循环计算。每次计算出两个位置上的数字,并且对其求和进行更新操作。
下面这个讲解很赞!!!
参考代码:
package leetcode_50; /*** * * @author pengfei_zheng * 实现大数相乘 */ public class Solution43 { public static String multiply(String num1, String num2) { int len1 = num1.length(); int len2 = num2.length(); int []pos = new int [len1+len2]; for(int i = len1-1; i>=0; i--){ for(int j = len2-1; j>=0; j--){ int mul = (num1.charAt(i)-'0')*(num2.charAt(j)-'0'); int p1 = i + j; int p2 = i + j + 1; int sum = mul + pos[p2]; pos[p1]+=sum/10; pos[p2]=sum%10; } } StringBuilder str = new StringBuilder(); for(int p: pos) if(!(str.length() == 0 && p == 0)) str.append(p); return str.length() == 0 ? "0" : str.toString(); } public static void main(String[]args){ System.out.println(multiply("987654321","123456789")); // ans = 121932631112635269 } }