标签: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 };
标签:style blog color os io ar for div log
原文地址:http://www.cnblogs.com/moderate-fish/p/3946724.html