Advertisement
asdfg0998

sol.cpp

Sep 10th, 2024
14
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. class Solution {
  2. public:
  3. // Function to multiply two numbers represented as strings
  4. string multiply(string num1, string num2) {
  5. // If either number is zero, the result is "0"
  6. if (num1 == "0" || num2 == "0") return "0";
  7.  
  8. int n = num1.size();
  9. int m = num2.size();
  10.  
  11. // Result vector to store the product (maximum length is n + m)
  12. vector<int> result(n + m, 0);
  13.  
  14. // Multiply each digit of num1 with each digit of num2
  15. for (int i = n - 1; i >= 0; --i) {
  16. for (int j = m - 1; j >= 0; --j) {
  17. int mul = (num1[i] - '0') * (num2[j] - '0'); // Multiply digits
  18.  
  19. int sum = mul + result[i + j + 1]; // Add to the existing result (carry handled)
  20.  
  21. result[i + j + 1] = sum % 10; // Store the current digit
  22. result[i + j] += sum / 10; // Handle carry over to the next digit
  23. }
  24. }
  25.  
  26. // Convert result vector to a string, skipping leading zeros
  27. string product = "";
  28. for (int num : result) {
  29. if (!(product.empty() && num == 0)) { // Skip leading zeros
  30. product += to_string(num);
  31. }
  32. }
  33.  
  34. return product.empty() ? "0" : product;
  35. }
  36.  
  37.  
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement