【每周例题】力扣 C++ 字符串相乘
字符串相乘
题目
题目分析
1.首先,题目上标出了一条:注意:不能使用任何内置的 BigInteger 库或直接将输入转换为整数。这就是这道题的难度所在
2.这样子的话,我们可以从手写乘法计算来寻找思路:
①首先我们需要将各位相乘的结果放入数组ansArr中,我们使用双重for循环计算num1与num2相乘
②我们将相乘的结果放入ansArr中,最后再进行进位计算
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | #include <iostream> #include <string> #include <vector> using namespace std; int main() { string num1, num2; cin >> num1 >> num2; //0乘任何数为0 if (num1 == "0" || num2 == "0" ) { cout << "0" ; return 0; } //计算num1,num2长度 int m = num1.size(), n = num2.size(); vector< int > ansArr(m + n, 0); // 初始化为0 //计算乘法 for ( int i = m - 1; i >= 0; i--) { int x = num1[i] - '0' ; for ( int j = n - 1; j >= 0; j--) { int y = num2[j] - '0' ; int sum = ansArr[i + j + 1] + x * y; //进位 ansArr[i + j + 1] = sum % 10; ansArr[i + j] += sum / 10; } } string ans; bool leadingZero = true ; // 用于跳过前导零 for ( int i = 0; i < m + n; i++) { if (ansArr[i] != 0 || !leadingZero) { leadingZero = false ; ans.push_back(ansArr[i] + '0' ); // 将整数转换为字符 } } cout << ans; return 0; } |
力扣代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class Solution { public : string multiply(string num1, string num2) { if (num1 == "0" || num2 == "0" ) return "0" ; int m = num1.size(), n = num2.size(); vector< int > ansArr(m + n, 0); // 初始化为0 for ( int i = m - 1; i >= 0; i--) { int x = num1[i] - '0' ; for ( int j = n - 1; j >= 0; j--) { int y = num2[j] - '0' ; int sum = ansArr[i + j + 1] + x * y; ansArr[i + j + 1] = sum % 10; ansArr[i + j] += sum / 10; } } string ans; bool leadingZero = true ; // 用于跳过前导零 for ( int i = 0; i < m + n; i++) { if (ansArr[i] != 0 || !leadingZero) { leadingZero = false ; ans.push_back(ansArr[i] + '0' ); // 将整数转换为字符 } } return ans; } }; |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步