使用 C++ 將兩個字串相乘並返回字串結果的程式


假設我們有兩個字串數字,我們需要將它們相乘並返回字串結果。例如,如果這兩個數字是“28”和“25”,那麼結果將是“700”

為此,我們需要按照以下步驟執行

  • 獲取兩個引數 x 和 y,其中 x 除以 y

  • 如果 x < −無窮大且 y = 1,則返回無窮大

  • a := |x|,b := |y|且 ans := 0

  • 當 a − b >= 0 時

    • p := 0

    • 當 a − (左移 b(左移 p 次)) >= 0 時

      • p := p + 1

    • a := a - (左移 b,p 次)

    • ans := ans + 左移 1 p 次

  • 如果 x > 0 為真且 y > 0 也為真,那麼返回 ans,否則返回(− ans)

以下實現可以幫助我們更好地理解,讓我們仔細看看

示例

 線上演示

#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");
}

輸入

"28", "25"

輸出

"700"

更新於: 2020 年 10 月 21 日

1K+ 次瀏覽

開啟您的事業

透過完成課程獲得認證

開始
廣告