• LeetCode(43. 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. 高位多个为0的,需要进行判断

    2. 如果乘数为0的话,可以直接跳过,能节省不少时间

    3. string 的两个使用

     1) 创建有 len 长的 ‘0’串  string str(len, '0')

     2) string 的反转 reverse(str.begin(), str.end())  反转后操作好像更容易理解~

     1 class Solution {
     2 public:
     3     string multiply(string num1, string num2) {
     4         int size1 = num1.size();
     5         int size2 = num2.size();
     6         string result(size1 + size2 + 1, '0');
     7         reverse(num1.begin(),num1.end());
     8         reverse(num2.begin(), num2.end());
     9         for(int j = 0; j < size2; ++j){//num2
    10             if(num2[j] == '0')
    11                 continue;
    12             int k = j;
    13             for(int i = 0; i < size1; ++i){//num1
    14                 int tmp = (num1[i] - '0') * (num2[j] - '0') + result[k] - '0';
    15                 result[k] = tmp % 10 + '0';
    16                 result[k + 1] = result[k + 1] + tmp / 10;
    17                 ++k;
    18             }
    19         }
    20         while(!result.empty() && result.back() == '0') result.pop_back();
    21         if(result.empty()) return "0";
    22         reverse(result.begin(), result.end());
    23         return result;
    24     }
    25 };
  • 相关阅读:
    Flesch Reading Ease(模拟)
    实验一:词法分析设计
    java—容器学习笔记
    [转载]马士兵Java视频教程 —— 学习顺序
    Java的安装过程
    编程之美初赛第一场
    RCC 2014 Warmup (Div. 2)
    ural 1017. Staircases(dp)
    ural 1012. K-based Numbers. Version 2(大数dp)
    ural 1009. K-based Numbers(简单dp)
  • 原文地址:https://www.cnblogs.com/coolqiyu/p/5332999.html
Copyright © 2020-2023  润新知