码迷,mamicode.com
首页 > 其他好文 > 详细

Multiply Strings

时间:2014-09-01 20:59:03      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   ar   for   div   log   

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.

思路:

 1 class Solution {
 2 public:
 3     string multiply( string num1, string num2 ) {
 4         reverse( num1.begin(), num1.end() );
 5         reverse( num2.begin(), num2.end() );
 6         string product( num1.length()+num2.length(), 0 );
 7         for( size_t i = 0; i != num1.length(); ++i ) {
 8             int carry = 0;
 9             for( size_t j = 0; j != num2.length(); ++j ) {
10                 carry += product[i+j]-0 + (num1[i]-0) * (num2[j]-0);
11                 product[i+j] = carry%10 + 0;
12                 carry /= 10;
13             }
14             int k = i + num2.length();
15             while( carry ) {
16                 carry = product[k]-0 + carry;
17                 product[k++] = carry%10 + 0;
18                 carry /= 10;
19             }
20         }
21         reverse( product.begin(), product.end() );
22         string::size_type pos = product.find_first_not_of( 0 );
23         return pos == string::npos ? "0" : product.substr(pos);
24     }
25 };

 

Multiply Strings

标签:style   blog   color   os   io   ar   for   div   log   

原文地址:http://www.cnblogs.com/moderate-fish/p/3946724.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!