• [leetcode] Multiply Strings


    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.
     
     
    分析:
    模拟手算乘法即可。分两部分:字符串的乘法,字符串的加法。
     
    例如:
              99
    *         12
    ------------------
             198
    +        99
    ------------------
             297
     
     1 class Solution
     2 {
     3 public:
     4   string add(string num1, string num2)
     5   {
     6     string ret = "";
     7     int flag = 0, temp = 0;
     8     int i = num1.size() - 1, j = num2.size() - 1;
     9 
    10     for(; i >= 0 || j >= 0; --i, --j)
    11     {
    12       if(i >= 0 && j >= 0)
    13         temp = num1[i] - '0' + num2[j] - '0' + flag;
    14       else if(i >= 0 && j < 0)
    15         temp = num1[i] - '0' + flag;
    16       else
    17         temp = num2[j] - '0' + flag;
    18 
    19       flag = temp / 10;
    20       temp = temp % 10;
    21       ret.insert(ret.begin(), '0' + temp);
    22     }
    23 
    24     if(flag == 1)
    25       ret.insert(ret.begin(), '1');
    26 
    27     return ret;
    28   }
    29   
    30 public:
    31   string multiply(string num1, string num2)
    32   {
    33     if(num1 == "0" || num2 == "0")
    34       return "0";
    35 
    36     string ret = "", str = "";
    37     int i = 0, j = 0, temp = 0, flag = 0;
    38 
    39     for(j = num2.size()-1; j>=0; --j)
    40     {
    41       str = "";
    42       flag = 0;
    43       for(i = num1.size()-1; i>=0; --i)
    44       {
    45         temp = (num1[i] - '0') * (num2[j] - '0') + flag;
    46         flag = temp / 10;
    47         temp = temp % 10;
    48         str.insert(str.begin(), temp + '0');
    49       }
    50       if(flag > 0)
    51         str.insert(str.begin(), flag + '0');
    52       
    53       for(int k = j; k < num2.size()-1; k++)
    54         str += "0";
    55       
    56       ret = add(str, ret);
    57     }
    58 
    59     return ret;
    60   }
    61 };
     
     
  • 相关阅读:
    利用python 传输文件
    SVN 操作报错 “Previous operation has not finished; run 'cleanup' if it was interrupted“
    Java IP白名单相关工具类
    Truncated class file 问题的解决
    Linux 文件压缩与解压相关
    MyEclipse 根据左括号或右括号查找另外一半
    100个常用的linux命令(转)
    Java 编码规范(转)
    MyEclipse 远程调试Tomcat
    Extjs header column 自定义排序规则
  • 原文地址:https://www.cnblogs.com/lxd2502/p/4269987.html
Copyright © 2020-2023  润新知