Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- // Function to multiply two numbers represented as strings
- string multiply(string num1, string num2) {
- // If either number is zero, the result is "0"
- if (num1 == "0" || num2 == "0") return "0";
- int n = num1.size();
- int m = num2.size();
- // Result vector to store the product (maximum length is n + m)
- vector<int> result(n + m, 0);
- // Multiply each digit of num1 with each digit of num2
- for (int i = n - 1; i >= 0; --i) {
- for (int j = m - 1; j >= 0; --j) {
- int mul = (num1[i] - '0') * (num2[j] - '0'); // Multiply digits
- int sum = mul + result[i + j + 1]; // Add to the existing result (carry handled)
- result[i + j + 1] = sum % 10; // Store the current digit
- result[i + j] += sum / 10; // Handle carry over to the next digit
- }
- }
- // Convert result vector to a string, skipping leading zeros
- string product = "";
- for (int num : result) {
- if (!(product.empty() && num == 0)) { // Skip leading zeros
- product += to_string(num);
- }
- }
- return product.empty() ? "0" : product;
- }
- };
Add Comment
Please, Sign In to add comment