LeetCode043 Multiply Strings

Input: num1 = “123”, num2 = “456”
Output: “56088”

pay attention: we are asked to: You must not use any built-in BigInteger library or convert the inputs to integer directly.

so it seems this problem is very easy to understand, but really hard to implement。

but the most important principle for this problem is: nums1.charAt(i)*nums2.charAt(j), the 个位数will be located at i+j+1, and its 进位will located at i+j.
and another thing we need to care about is: everytime we calculate nums1.charAt(i)*nums2.charAt(j), we also need to add the 进位of previous

class Solution {
    public String multiply(String num1, String num2) {
        if (num1 == null || num2 == null) return "0"; //特殊情况
        int[] digits = new int[num1.length() + num2.length()]; // 先确定下来两个数乘积的位数是两个数之和
        for (int i = num1.length() -1; i >= 0; i--) { //
            for (int j = num2.length()-1; j >= 0; j--) { //每个字符串的指针都从后向前遍历
                int product = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); // 计算同位置处的乘积
                int p1 = i + j, p2 = i + j + 1; //很是奇妙 第一个字符的i位和第二个字符的j位的最终乘积个位数所处的位置为最终的i+j+1位置,所以我们用p1来承接进位 p2来承接个位
                int sum = product + digits[p2]; // 同样还要承接上一个的进位
                digits[p1] += sum / 10; //p1位置作为更高的次位 更新i+j位
                digits[p2] = sum % 10; //p2位置作为低一级的次位 //更新i+j+1位
            }
        } //这个for语句构建起了digits这个数组
        StringBuilder res = new StringBuilder();
        for (int digit : digits) { // 对于digits数组中的每一位,注意,这是从头开始遍历,也就是说,如果
            if (!(digit == 0 && res.length() == 0)) { //这个数组前几位是0的话,下面的语句根本不会执行
                res.append(digit); // 只有在第一个不为0的数开始才开始append
            }
        }//所以这个for语句是相当于trim()函数?
        return res.length() == 0 ? "0" : res.toString(); //最后检查是否为0?不为0就转化为String
    }
}
posted @ 2020-06-12 08:02  EvanMeetTheWorld  阅读(19)  评论(0)    收藏  举报