[刷题防痴呆] 0043 - 字符串相乘 (Multiply S

2021-10-23  本文已影响0人  西出玉门东望长安

题目地址

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

题目描述

43. Multiply Strings

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:

Input: num1 = "123", num2 = "456"
Output: "56088"

思路

关键点

代码

class Solution {
    public String multiply(String num1, String num2) {
        int m = num1.length();
        int n = num2.length();

        int[] arr = new int[m + n];
        for (int i = m - 1; i >= 0; i--) {
            for (int j = n - 1; j >= 0; j--) {
                int product = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
                int p1 = i + j;
                int p2 = i + j + 1;
                int sum = arr[p2] + product;
                arr[p1] += sum / 10;
                arr[p2] = sum % 10;
            }
        }

        StringBuffer sb = new StringBuffer();
        int index = 0;
        while (index < arr.length && arr[index] == 0) {
            index++;
        }
        while (index < arr.length) {
            sb.append(arr[index]);
            index++;
        }
        if (sb.length() == 0) {
            return "0";
        }
        return sb.toString();
    }
}
上一篇下一篇

猜你喜欢

热点阅读