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
  • 相关阅读:
    【pywin32总结】
    python 操作 office
    Python操作Word【批量生成文章】
    该怎样用几何画板绘制正五边形呢
    安装ChemOffice 15.1就是这么简单
    MathType编辑钢筋符号就是这么简单
    该如何将MathType公式粘贴到文档中
    修改Chem 3D模型的化学键属性的方法有哪些
    几何画板做圆柱的方法有哪些
    用几何画板如何实现抛物线左右平移
  • 原文地址:https://www.cnblogs.com/freeneng/p/3218928.html
Copyright © 2011-2022 走看看