Multiply Strings [LeetCode]

Problem Description http://oj.leetcode.com/problems/multiply-strings/

Basic idea is to multiply two nums like we do caculation on paper, one by one digital multiplication, then add the temporary results together to get the final one. Be careful about the last carry digital.

 class Solution {
public:
string multiply_one_digital(char c, string num2, int tail){
string result;
for(int i = ; i < tail; i ++) {
result.push_back('');
} int carry = ;
for(int i = num2.size() - ; i >= ; i-- ) {
int one_result = (c - ) * (num2[i] - ) + carry;
carry = one_result/;
char current_digital = one_result % + ;
result.insert(result.begin(),current_digital);
} if(carry > )
result.insert(result.begin(), (char)(carry + )); return result;
} string multiply(string num1, string num2) {
// Note: The Solution object is instantiated only once and is reused by each test case.
string result;
if(num1.size() == || num2.size() == )
return result;
if((num1.size() == && num1[] == '') ||
(num2.size() == && num2[] == '')) {
result.push_back('');
return result;
} vector<string> tmp_results;
for(int i = num1.size() - ; i >= ; i -- ) {
if(num1[i] == '')
continue; tmp_results.push_back(multiply_one_digital(num1[i], num2, num1.size() - - i));
} //add all temporary results
string last_tmp_result = tmp_results[tmp_results.size() - ];
int carry = ;
for(int i = ; i < last_tmp_result.size(); i ++ ){
int one_result = ;
for( auto item: tmp_results) {
if(i > item.size() - )
continue; one_result += (item[item.size() - - i] - );
} one_result += carry;
carry = one_result/;
char current_digital = one_result % + ;
result.insert(result.begin(),current_digital);
} if(carry > )
result.insert(result.begin(), (char)(carry + )); return result;
}
};
上一篇:robot framework 接口测试 http协议post请求json格式


下一篇:RESTFul中的那些事(1)---在RESTFul中,HTTP Put和Patch操作的差别?