zoukankan      html  css  js  c++  java
  • [Leetcode 90] 43 Multiply Strings

    Problem:

    Given two numbers represented as strings, return multiplication of the numbers as a string.

    Note: The numbers can be arbitrarily large and are non-negative.

    Analysis:

    It's the big number simulation problem. Recall the process how we compute the multiplication manually. Multiply the tow numbers digit by digit and sum the result up. Use a char array to store the result reversely and after the computing reverse it to the normal order. Pay attention of the carry bit and the space allocated to the result array (l1+l2+1 is definitely enough but l1+l2 is not). Also, if one of the given number is 0, just return 0 and don't bother to compute it even.

    Code:

     1 class Solution {
     2 public:
     3    string multiply(string num1, string num2) {
     4     // Start typing your C/C++ solution below
     5     // DO NOT write int main() function
     6     if (num1 == "0" || num2 == "0")
     7         return "0";
     8     
     9     int l1 = num1.length(), l2 = num2.length(), idx, cry;
    10     char *res = new char[l1+l2+1];
    11 
    12     for (int i=0; i<l1+l2; i++)
    13         res[i] = '0';
    14 
    15     for (int i=l1-1, inc=0; i>=0; i--, inc++) {
    16         idx = inc, cry = 0;
    17         for (int j=l2-1; j>=0; j--) {
    18             int mul = (num1[i]-'0') * (num2[j]-'0') + cry + (res[idx]-'0');
    19 
    20             res[idx] = ( mul % 10 ) + '0';
    21             cry = mul / 10;
    22             idx++;
    23         }
    24 
    25         if (cry > 0)
    26             res[idx] = cry + '0';
    27     }
    28 
    29     if (cry > 0)
    30         res[idx++] = cry + '0';
    31 
    32     res[idx] = '';
    33 
    34     for (int i=0, j=idx-1; i < j; i++, j--) {
    35         char t = res[i];
    36         res[i] = res[j];
    37         res[j] = t;
    38     }
    39 
    40     string r(res);
    41 
    42     return r;
    43 }
    44 };
    View Code
  • 相关阅读:
    url处理函数
    各种排序方法(冒泡,快速,插入,选择),二分查找
    js二叉树,前序/中序/后序(最大最小值,排序)
    vs中nuget命令的用法
    父子页面间调用
    Ubuntu16.04.2 LTS下使用编译安装程序(使用configure、make、 make install)
    windows与虚拟机的linux共享一个文件夹
    Linux下安装nginx
    Linux下安装VSCode
    Ubuntu下安装jdk
  • 原文地址:https://www.cnblogs.com/freeneng/p/3218928.html
Copyright © 2011-2022 走看看