zoukankan      html  css  js  c++  java
  • 19.2.4 [LeetCode 43] 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.

    Example 1:

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

    Example 2:

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

    Note:

    1. The length of both num1 and num2 is < 110.
    2. Both num1 and num2 contain only digits 0-9.
    3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
    4. You must not use any built-in BigInteger library or convert the inputs to integer directly.
     1 class Solution {
     2 public:
     3     string multiply(string num1, string num2) {
     4         reverse(num1.begin(), num1.end());
     5         reverse(num2.begin(), num2.end());
     6         int nn[250] = { 0 }, maxl = 0;
     7         int l1 = num1.length(), l2 = num2.length();
     8         for(int i=0;i<l1;i++)
     9             for (int j = 0; j < l2; j++) {
    10                 nn[i + j] += (num1[i] - '0')*(num2[j] - '0');
    11                 int tmp = i + j;
    12                 while (nn[tmp] > 9) {
    13                     nn[tmp + 1] += nn[tmp] / 10;
    14                     nn[tmp] %= 10;
    15                     tmp++;
    16                 }
    17                 if (nn[tmp] == 0)continue;
    18                 maxl = max(tmp, maxl);
    19             }
    20         string ans = "";
    21         for (int i = maxl; i >= 0; i--) {
    22             char ch = nn[i] + '0';
    23             ans += ch;
    24         }
    25         return ans;
    26     }
    27 };
    View Code

    大整数乘法

  • 相关阅读:
    2017 9 26
    NOI2002 银河英雄传说(luogu p1196)
    luogu [USACO08OCT]打井Watering Hole
    luogu P2784 化学1(chem1)- 化学合成
    2017 9 24
    2017.9.24 noip模拟赛 day2—组合数
    Java 接口——2
    Java 接口——1
    Java 泛型
    Java 随笔——8
  • 原文地址:https://www.cnblogs.com/yalphait/p/10351729.html
Copyright © 2011-2022 走看看