• leetcode-multiply strings


    这道题就是大数运算。

    lexi's的想法很好,在操作之前先把num1和num2给逆置,方便操作。 

    Tenos的文章通过一张图把计算过程直观的展示出来。

    image

     1 class Solution {
     2 public:
     3     string multiply(string num1, string num2) {
     4         int m = num1.size(); int n = num2.size();
     5         int *d = new int[m+n];
     6         fill_n(d,m+n,0);    
     7         reverse(num1.begin(),num1.end());
     8         reverse(num2.begin(),num2.end());
     9         for (int i = 0; i < m; i++)
    10         {
    11             for (int j = 0; j < n; j++)
    12             {
    13                 d[i + j] +=(num1[i]-'0')*(num2[j]-'0');
    14             }
    15         }
    16         string res("");
    17         for (int i = 0; i < m + n; i++)
    18         {
    19             int digit = d[i] % 10;
    20             int carry = d[i] / 10;
    21             res.insert(0,1,char(digit+'0'));//注意在插入char元素时的用法。
    22             if (i < m + n - 1) d[i + 1] += carry;
    23         }
    24         //此时有可能前面的(下标小的)一些元素是0,要去除。
    25         while (res[0] == '0' && res.length()>1)//是>1,不能是>0,否则结果为0时就删空了。
    26         {
    27             res.erase(res.begin());
    28         }
    29         return res;
    30     }
    31 };

    Ref:

    http://leetcodenotes.wordpress.com/2013/10/20/leetcode-multiply-strings-%E5%A4%A7%E6%95%B4%E6%95%B0%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B9%98%E6%B3%95/

    http://www.cnblogs.com/TenosDoIt/p/3735309.html

  • 相关阅读:
    Delphi IDE 设置
    我最喜欢的歌曲
    Window 常用文件
    Delphi TTable 组件
    Delphi TDatabase 组件
    c语言->和 .
    Shell 工具之 gawk
    Shell 工具之 sed
    Shell 语法之函数
    Shell 语法之信号与作业
  • 原文地址:https://www.cnblogs.com/forcheryl/p/4090880.html
Copyright © 2020-2023  润新知