弱鸡思维
string multiply(string num1, string num2)
{
long ans1 = 0, ans2 = 0;
for (int i = 0; i < num1.length(); i++)
{
ans1 = ans1 * 10 + (num1[i] - '0');
}
for (int i = 0; i < num2.length(); i++)
{
ans2 = ans2 * 10 + (num2[i] - '0');
}
return to_string(ans1 * ans2);
}
可以通过一些测试点,但是当这个字符串太大会long long也会越界的,
献上大佬的思路:
class Solution {
public:
string multiply(string num1, string num2) {
int n1 = num1.length();
int n2 = num2.length();
string res(n1 + n2, '0');
for (int i = n2 - 1; i >= 0; i--) {
for (int j = n1 - 1; j >= 0; j--) {
int temp = (res[i + j + 1] - '0') + (num1[j] - '0')*(num2[i] - '0');
res[i + j + 1] = temp % 10 + '0';//当前位
res[i + j] += temp / 10;
}
}
for (int i = 0; i < n1 + n2; i++) {
if (res[i] != '0')
return res.substr(i);
}
return "0";
}
};
之后我想到了这个和PAT乙级的一个题目很相像,有兴趣可以看一下嗷,放上链接和我的AC代码1017 A除以B (20分)
#include<iostream>
#include<iostream>
using namespace std;
int main()
{
string A;
int Q,B, R;
cin >> A >> Q;
B = (A[0] - '0') / Q;
if (B != 0 && A.length() > 1||A.length()==1)
cout << B;
R = (A[0] - '0') % Q;
for (int i = 1; i < A.length(); i++)
{
B = ((R * 10) + (A[i] - '0'))/Q;
cout << B;
R = (R * 10 + (A[i] - '0')) % Q;
}
cout << " " << R;
system("pause");
return 0;
}