标签:
题目描述:(链接)
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 int len1 = num1.size(); 5 int len2 = num2.size(); 6 7 int len = len1 + len2; 8 string r(len, ‘0‘); 9 10 for (int i = 0; i < len1; ++i) { 11 int carry = 0; 12 int a = num1[len1 - i - 1] - ‘0‘; 13 for (int j = 0; j < len2; ++j) { 14 int b = num2[len2 - j - 1] - ‘0‘; 15 int sum = a * b + r[i + j] - ‘0‘ + carry; 16 r[i + j] = sum % 10 + ‘0‘; 17 carry = sum / 10; 18 } 19 20 if (carry > 0) { 21 r[i + len2] += carry; 22 } 23 } 24 25 int start = 0; 26 for (int i = len - 1; i >= 0; --i) { 27 if (r[i] != ‘0‘) { 28 start = i; 29 break; 30 } 31 } 32 33 string result; 34 for (int i = start; i >= 0; --i) { 35 result += r[i]; 36 } 37 38 return result; 39 } 40 };
标签:
原文地址:http://www.cnblogs.com/skycore/p/5062686.html