/
DeC2018
/
0043
Обзор
Документация
Войти
/
DeC2018
/
0043
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
main.cpp
61 строка
2 KB
Den
create main.cpp
26 янв 2025, 22:11
26 янв 2025, 22:11
1641f14
Код
Авторство
О чём код?
#include <iostream> #include <vector> #include <string> using namespace std; class Solution { public: string multiply(string num1, string num2) { vector<int> num1Digits, num2Digits; // Convert num1 to an integer representation using a vector for (char c : num1) { num1Digits.push_back(c - '0'); } // Convert num2 to an integer representation using a vector for (char c : num2) { num2Digits.push_back(c - '0'); } // Initialize the result vector with size of the combined lengths of num1 and num2 vector<int> result(num1Digits.size() + num2Digits.size(), 0); // Perform the multiplication digit by digit for (int i = num1Digits.size() - 1; i >= 0; i--) { for (int j = num2Digits.size() - 1; j >= 0; j--) { int mul = num1Digits[i] * num2Digits[j]; int sum = mul + result[i + j + 1]; result[i + j + 1] = sum % 10; result[i + j] += sum / 10; } } // Convert the result vector back to a string string resultStr; for (int num : result) { if (!(resultStr.empty() && num == 0)) { resultStr.push_back(num + '0'); } } return resultStr.empty() ? "0" : resultStr; } }; int main() { Solution solution; string num1 = "2"; string num2 = "3"; cout << "Input: num1 = \"" << num1 << "\", num2 = \"" << num2 << "\"" << endl; cout << "Output: \"" << solution.multiply(num1, num2) << "\"" << endl; num1 = "123"; num2 = "456"; cout << "Input: num1 = \"" << num1 << "\", num2 = \"" << num2 << "\"" << endl; cout << "Output: \"" << solution.multiply(num1, num2) << "\"" << endl; return 0; }