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
  • 相关阅读:
    HDU 6984
    洛谷 P6776
    C语言 error C4996: This function or variable may be unsafe
    C语言 sizeof 函数
    C语言 strlen 函数
    C语言 char 字符串
    C语言 goto 语句
    C语言 switch 语句
    C语言 do while 和 while 循环
    C语言 while 循环
  • 原文地址:https://www.cnblogs.com/freeneng/p/3218928.html
Copyright © 2011-2022 走看看