zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    协议(五)-从电报机到智能手机
    协议(四)-通信发展史
    NDK历史版本
    android onKeyDown
    设计模式
    Android获取系统时间的多种方法
    USB 3.0规范中译本 第5章 机械结构
    ES6新特性
    08_SQLyog图形化工具介绍
    07_聚合函数,分组查询&limit关键字
  • 原文地址:https://www.cnblogs.com/forcheryl/p/4090880.html
Copyright © 2011-2022 走看看