加法乘法模拟

题目 字符串相乘43. 字符串相乘 - 力扣(LeetCode) (leetcode-cn.com)

无论是模拟乘法还是加法,流程都可归纳为:

循环按位加法或者乘法运算得到tempres->curr(tempres/10)->进位carry(tempres%进制)

 1 class Solution {
 2 public:
 3     string multiply(string num1, string num2) {
 4         if (num1 == "0" || num2 == "0") {
 5             return "0";
 6         }
 7         string ans = "0";
 8         int m = num1.size(), n = num2.size();
 9         for (int i = n - 1; i >= 0; i--) {//num2每一位与num1相乘
10             string curr;
11             int add = 0;
12             for (int j = n - 1; j > i; j--) {
13                 curr.push_back(0);
14             }
15             int y = num2.at(i) - '0';
16             for (int j = m - 1; j >= 0; j--) {
17                 int x = num1.at(j) - '0';
18                 int product = x * y + add;
19                 curr.push_back(product % 10);
20                 add = product / 10;
21             }
22             while (add != 0) {
23                 curr.push_back(add % 10);
24                 add /= 10;
25             }
26             reverse(curr.begin(), curr.end());
27             for (auto &c : curr) {
28                 c += '0';
29             }
30             ans = addStrings(ans, curr);
31         }
32         return ans;
33     }
34     //字符串相加
35     string addStrings(string &num1, string &num2) {
36         int i = num1.size() - 1, j = num2.size() - 1, add = 0;
37         string ans;
38         while (i >= 0 || j >= 0 || add != 0) {
39             int x = i >= 0 ? num1.at(i) - '0' : 0;
40             int y = j >= 0 ? num2.at(j) - '0' : 0;
41             int result = x + y + add;
42             ans.push_back(result % 10);
43             add = result / 10;
44             i--;
45             j--;
46         }
47         reverse(ans.begin(), ans.end());
48         for (auto &c: ans) {
49             c += '0';
50         }
51         return ans;
52     }
53 };
原文地址:https://www.cnblogs.com/qianxunslimg/p/15642438.html