We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3" Output: "6"
Example 2:
Input: num1 = "123", num2 = "456" Output: "56088"
Note:
大数相乘。乘法本质上就是移位的加法,所以我的思路是第一个字符串对第二个字符串的每位字符相乘,左移,将得到的结果相加就是答案。 我的做法如下:
class Solution { public: string multiply(string num1, string num2) { string res; int n2 = num2.length(); for (int i = n2 - 1; i >= 0; --i) { string s = singleMul(num1, num2[i] - '0', n2 - i - 1); res = strAdd(res, s); } // 判断字符串是否为全0 for (int i = 0; i < res.length(); ++i) { if (res[i] != '0') return res; } return "0"; } //相乘函数 string singleMul(string num, int k, int p) { int n1 = num.length(); int up = 0; for (int i = n1 - 1; i >= 0; --i) { char ch = num[i]; int aInt = ch - '0'; ch = (aInt * k + up) % 10 + '0'; up = (aInt * k + up) / 10; num[i] = ch; } //如果还有进位,则要插入到字符串最前 if (up) { num.insert(0, 1, up + '0'); } while (p > 0) { num.push_back('0'); --p; } return num; } //字符串相加函数 string strAdd(string res, string s) { string result; int resLen = res.length(), sLen = s.length(); if (resLen == 0) return s; int i = resLen - 1, j = sLen - 1; int up = 0; while (i >= 0 && j >= 0) { int a = (res[i] - '0') + (s[j] - '0') + up; result.push_back(a % 10 + '0'); up = a / 10; --i; --j; } while (i >= 0) { char ch = (res[i] - '0' + up) % 10 + '0'; up = (res[i] - '0' + up) / 10; result.push_back(ch); --i; } while (j >= 0) { char ch = (s[j] - '0' + up) % 10 + '0'; up = (s[j] - '0' + up) / 10; result.push_back(ch); --j; } //不要忘了也要算进位 if (up != 0) result.push_back(up + '0'); i = 0; j = result.length() - 1; //因为顺序是反着的,所以字符串要翻转一遍 while (i < j) { char temp = result[i]; result[i] = result[j]; result[j] = temp; ++i; --j; } return result; } };
遇到的困难点:
参考资料:
The text was updated successfully, but these errors were encountered:
No branches or pull requests
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Example 1:
Example 2:
Note:
大数相乘。乘法本质上就是移位的加法,所以我的思路是第一个字符串对第二个字符串的每位字符相乘,左移,将得到的结果相加就是答案。
我的做法如下:
遇到的困难点:
参考资料:
The text was updated successfully, but these errors were encountered: