zoukankan      html  css  js  c++  java
  • 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()
        }
    }
  • 相关阅读:
    0909初识操作系统
    实验四主存空间的分配和回收
    实验一 DOS命令解释程序的编写
    0909关于操作系统
    实验四主存空间的分配和回收
    实验3评价
    实验一 DOS命令解释程序的编写
    实验三、进程调度模拟程序实验
    实验二、作业调度实验
    0909 第一次上机课之《为什么学操作系统?》
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/14184134.html
Copyright © 2011-2022 走看看