Leetcode:43. Multiply Strings

Description

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

  • The length of both num1 and num2 is < 110.
  • Both num1 and num2 contains only digits 0-9.
  • Both num1 and num2 does not contain any leading zero.
  • You must not use any built-in BigInteger library or convert the inputs to integer directly.

思路

  • 按照乘法的过程来,中间主要考虑到进位问题

代码

class Solution {
public:
    string multiply(string num1, string num2) {
		int len1 = num1.size();
		int len2 = num2.size();
		string str(len1 + len2 + 1, '0');

		int count = 0;
		int mul = 0;
		int start = 0;
		int i = 0;
		for (i = len2 - 1; i >= 0; --i){
			for (int j = len1 - 1; j >= 0; --j){
				mul = (num2[i] - '0') * (num1[j] - '0') + (str[start + len1 - 1 - j] - '0') + count;
				count = mul / 10;
				str[start + len1 - 1 - j] = '0' + (mul % 10);
			}

			if (count > 0){
				str[start + len1] = '0' + count;
				count = 0;
			}

			start++;
		}

		string tmp;
		for (i = str.size() - 1; i >= 0; --i){
			if (str[i] != '0')  break;
		
		for (int j = i; j >= 0; --j)
			tmp += str[j];

		if (tmp.empty()) return "0";
		return tmp;
	}
};
posted @ 2017-05-12 15:21  JeffLai  阅读(190)  评论(0编辑  收藏  举报