43. Multiply Strings

复制代码
package LeetCode_43

/**
 * 43. Multiply Strings
 * https://leetcode.com/problems/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.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.

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

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

Constraints:
1. 1 <= num1.length, num2.length <= 200
2. num1 and num2 consist of digits only.
3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
 * */
class Solution {
    /*
    * solution: new array to save the multiplication result of each number, for example: 123*45:
    *   123, index i
    *    45, index j
    * ------
    *    15  index: i+j, i+j+1
    *   10
    *  05
    *   12
    *  08
    * 04
    * ------
    * 01234  new_index
    *
    * Time:O(m*m), Space:O(m+n)
    * */
    fun multiply(num1: String, num2: String): String {
        val m = num1.length
        val n = num2.length
        val array = IntArray(m + n)
        for (i in m - 1 downTo 0) {
            for (j in n - 1 downTo 0) {
                val cur = (num1[i] - '0') * (num2[j] - '0')
                array[i + j + 1] += cur
                if (array[i + j + 1] >= 10) {
                    //sum up carry and save in left of (i + j + 1)
                    array[i + j] += (array[i + j + 1]) / 10
                    //update current digit
                    array[i + j + 1] = (array[i + j + 1]) % 10
                }
            }
        }
        val result = StringBuilder()
        for (num in array) {
            if (!(result.isEmpty() && num == 0)) {
                result.append(num)
            }
        }
        return if (result.isEmpty()) "0" else result.toString()
    }
}
复制代码

 

posted @   johnny_zhao  阅读(97)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-12-24 Daily Coding Problem: Problem #393
点击右上角即可分享
微信分享提示