LeetCode 43. Multiply Strings

Implement the mul function of the string yourself. The given string meets the requirements of the number. Very simple Solution
considers the carry and index in the middle.

class Solution {
    public String multiply(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0")) {
            return "0";
        }
        char[] char1 = num1.toCharArray();
        char[] char2 = num2.toCharArray();
        int len1 = num1.length();
        int len2 = num2.length();
        int[] res = new int[len1 + len2];
        for (int i = len1 - 1; i >= 0; i--) {
            int carry = 0; // 进位
            int index = res.length - 1 - (len1 - 1 - i); // 相对坐标
            for (int j = len2 - 1; j >= 0; j--) {
                int mul = res[index] + (char1[i] - '0')*(char2[j] - '0') + carry;
                carry = mul/10;
                res[index] = mul%10;
                index--;
            }
            res[index] += carry; // 如果有进位的话
        }
        StringBuilder sb = new StringBuilder();
        boolean flag = true;
        for (int i = 0; i < res.length; i++ ) {
            if (res[i] == 0 && flag) {
                continue;
            }
            flag = false;
            sb.append(res[i] + "");
        }
        return sb.toString();
    }
}

Pythonis just a joke :blush:

class Solution:
    def multiply(self, num1, num2):
        """
        :type num1: str
        :type num2: str
        :rtype: str
        """
        return str(int(num1)*int(num2))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326486735&siteId=291194637