在 C++ 中乘以字符串

pythonserver side programmingprogramming更新于 2025/10/25 16:44:17

假设我们有两个数字作为字符串。我们必须将它们相乘并以字符串形式返回结果。因此,如果数字是"26"和"12",则结果将是"312"

要解决这个问题,我们将遵循以下步骤 −

  • 取两个参数 x 和 y,表示 x 除以 y
  • 如果 x < -Infinity 且 y = 1,则返回无穷大
  • a := |x|,b := |y| 和 ans := 0
  • 当 a – b >= 0
    • p := 0
    • while a – (左移 b (左移 1 p 次)) >= 0
      • p := p + 1
    • a := a – (左移 b,p 次)
    • ans := ans + 左移 1 p 次
  • 如果 x > 0 为真且 y > 0 也为真,则返回 ans,否则返回 (– ans)

示例(C++)

让我们看下面的实现,以便更好地理解 −

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   string multiply(string num1, string num2);
};
string Solution::multiply(string nums1, string nums2) {
   int n = nums1.size();
   int m = nums2.size();
   string ans(n + m, '0');
   for(int i = n - 1; i>=0; i--){
      for(int j = m - 1; j >= 0; j--){
         int p = (nums1[i] - '0') * (nums2[j] - '0') + (ans[i + j + 1] - '0');
         ans[i+j+1] = p % 10 + '0';
         ans[i+j] += p / 10 ;
      }
   }
   for(int i = 0; i < m + n; i++){
      if(ans[i] !='0')return ans.substr(i);
   }
   return "0";
}
main(){
   Solution ob;
   cout << ob.multiply("28", "25");
}

输入

"26"
"12"

输出

"312"

相关文章


有用资源