首页 > 代码库 > 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.
思路:
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。