multiply Strings

参考:https://www.cnblogs.com/TenosDoIt/p/3735309.html

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative

大整数乘法


我们以289*785为例

image

首先我们把每一位相乘,得到一个没有进位的临时结果,如图中中间的一行红色数字就是临时结果,然后将各位置的临时结果相加(图中红色),再从低位起依次进位。对于一个m位整数乘以n位整数的结果,最多只有m+n位,最少也有m+n-1位。

用一个长为m+n的数组存放每一位的临时结果相加的和(红色),对于原来两个数的位置i,j,在最后结果的位置为i+j+1;

class Solution {
    public String multiply(String num1, String num2) {
        //两个数相乘,最大m+n位
        if(num1.equals("0")||num2.equals("0")) return "0";
        int m=num1.length();
        int n=num2.length();
        int[] products=new int[m+n];
        for(int i=m-1;i>=0;i--)
            for(int j=n-1;j>=0;j--)
                products[i+j+1]+=(num1.charAt(i)-'0')*(num2.charAt(j)-'0');
        
        int digit=0;
        StringBuilder sb=new StringBuilder();
        for(int i=m+n-1;i>=0;i--){
            int tem=products[i]+digit;
            sb.append(tem%10);
            digit=tem/10;
        }
        sb.reverse();
        if(sb.charAt(0)=='0') sb.deleteCharAt(0);
        return sb.toString();
    }
}
原文地址:https://www.cnblogs.com/xiaolovewei/p/8177823.html