首页 > 代码库 > 【LeetCode】Multiply Strings
【LeetCode】Multiply Strings
Multiply Strings
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
我借鉴了
class Solution {public: string multiply(string num1, string num2) { int m = num1.size(); int n = num2.size(); //record each digit of result in reverse order vector<int> result(m+n, 0); //num index, the rightmost denotes as 0 int ind1 = 0; int ind2 = 0; for(int i = m-1; i >= 0; i --) { int carrier = 0; int n1 = num1[i]-‘0‘; //for every digit in num1, the num2 start with the rightmost digit ind2 = 0; for(int j = n-1; j >= 0; j --) { int n2 = num2[j]-‘0‘; int product = n1*n2 + result[ind1+ind2] + carrier; carrier = product/10; result[ind1+ind2] = product%10; ind2 ++; } //all digits in num2 finished multiplication with num1[i] //the remaining carrier added in the right position result[ind1+ind2] += carrier; ind1 ++; } //skip 0s in the right of result while(result.size() > 0 && result[result.size()-1] == 0) result.pop_back(); if(result.empty()) return "0"; else { string s; int i = result.size(); while(i --) s += (‘0‘+result[i]); return s; } }};
【LeetCode】Multiply Strings
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。