leetcode 43. Multiply Strings | 43. 字符串相乘(Java)

x33g5p2x  于2021-11-12 转载在 Java  
字(1.1k)|赞(0)|评价(0)|浏览(264)

题目

https://leetcode.com/problems/multiply-strings/

题解

模拟手动乘法,列竖式

class Solution {
    public String multiply(String num1, String num2) {
        // guarantee len(num1) > len(num2)
        if (num1.length() < num2.length()) {
            String t = num1;
            num1 = num2;
            num2 = t;
        }
        
        // simulate human multiply
        String[] arr = new String[num2.length()];
        for (int i = num2.length() - 1, zero = 0; i >= 0; i--, zero++) {
            arr[i] = mul(num1, num2.charAt(i) - '0', zero);
        }
        StringBuilder result = new StringBuilder();
        int carry = 0;
        for (int i = arr[0].length() - 1; i >= 0; i--) {
            int cur = carry;
            for (String a : arr) {
                cur += a.charAt(i) - '0';
            }
            carry = cur / 10;
            result.insert(0, cur % 10);
        }
        
        // remove leading zero
        while (result.length() > 0 && result.charAt(0) == '0') {
            result.deleteCharAt(0);
        }
        return result.length() == 0 ? "0" : result.toString();
    }
	// 多位数 * 一位数
    public String mul(String num, int single, int zero) {
        StringBuilder result = new StringBuilder();
        int carry = 0;
        for (int i = num.length() - 1; i >= 0; i--) {
            int cur = carry + (num.charAt(i) - '0') * single;
            carry = cur / 10;
            result.insert(0, cur % 10);
        }
        if (carry > 0) result.insert(0, carry);
        return result.append("0".repeat(zero)).insert(0, "0".repeat(num.length() * 2 - result.length())).toString();
    }
}

相关文章

最新文章

更多