zoukankan      html  css  js  c++  java
  • [LeetCode] Multiply Strings

    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.

    乘法原理,感觉如果用数组来计算会简单很多,用字符串必须再每次循环后处理一下高位的进位问题,比较麻烦。

     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         string s(num1.size() + num2.size(), '0');
     7         
     8         reverse(num1.begin(), num1.end());
     9         reverse(num2.begin(), num2.end());
    10         
    11         for(int i = 0; i < num1.size(); i++)
    12         {
    13             int flag = 0;
    14             for(int j = 0; j < num2.size(); j++)
    15             {
    16                 int digit = s[i+j] - '0';
    17                 int num = (num1[i] - '0') * (num2[j] - '0');
    18                 int res = digit + num + flag;
    19                 s[i+j] = (res % 10) + '0';
    20                 flag = res / 10;
    21             }
    22             int index = i + num2.size();
    23             while(flag)
    24             {
    25                 int digit = s[index] - '0';
    26                 int res = digit + flag;
    27                 s[index] = (res % 10) + '0';
    28                 flag = res / 10;
    29             }
    30         }
    31         
    32         while(true)
    33         {
    34             if (s[s.size()-1] == '0' && s.size() > 1)
    35                 s.erase(s.size() - 1, 1);
    36             else
    37                 break;
    38         }
    39         
    40         reverse(s.begin(), s.end());
    41         
    42         return s;
    43     }
    44 };
  • 相关阅读:
    对Promise的研究4
    对Promise的研究3
    对Promise的研究2
    对promise的研究1
    数据结构_栈
    数据结构_队列(普通队列和双端队列)
    数据结构_链表(单链表,单向循环链表,双链表)
    数据库进行参数化,查询一行或多行语句
    数据库基础应用
    选择排序
  • 原文地址:https://www.cnblogs.com/chkkch/p/2774129.html
Copyright © 2011-2022 走看看