Fork me on GitHub

43. Multiply Strings

43. Multiply Strings

题目

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.

解析

  • 大数相乘原则
  • 认清楚乘法从后面开始乘,vec[size-1]是最小位
string multiply(string num1, string num2) {
	int l1 = num1.size(), l2 = num2.size();
	string res(l1 + l2, '0');
	if (l1 == 0 || l2 == 0)
		return "";
	for (int i = l1 - 1; i >= 0; i--){
		int add = 0;
		for (int j = l2 - 1; j >= 0; j--){
			int mul = (num1[i] - '0')*(num2[j] - '0');
			int sum = res[i + j + 1] + add + mul % 10 - '0';
			res[i + j + 1] = '0' + sum % 10;
			add = mul / 10 + sum / 10;
		}
		res[i] += add;
	}
	for (int i = 0; i < l1 + l2; i++)
	if (res[i] != '0')
		return res.substr(i);
	return "0";
}

int main()
{
	string str1, str2;
	cin >> str1;
	cin >> str2;

	string ret = multiply(str1, str2);

	cout << ret << endl;
	return 0;
}
  • 自己实现
// add 43. Multiply Strings
class Solution_43 {
public:
	string multiply(string num1, string num2) {
		int len1 = num1.size();
		int len2 = num2.size();

		vector<int> vec(len1+len2,0); // 初始化内存空间
		//vec.reserve(len1 + len2);
		
		for (int i = 0; i < len1; i++)
		{
			int k = i;
			for (int j = 0; j < len2;j++)
			{
				//vec.push_back(a*b);
				vec[k] += (num1[len1-1-i] - '0')*(num2[len2-1-j]-'0');	////Calculate from rightmost to left
				k++; 
			}
		}

		string ret="";
		for (int i = 0; i < vec.size();i++)
		{
			if (vec[i]>=10)
			{
				vec[i+1] += vec[i] / 10;
				vec[i] = vec[i] % 10;
			}
			//char temp[5];
			//_itoa(vec[i], temp, 10);
			//ret += temp;

			char temp = vec[i] + '0'; 
			ret += temp; //反着取得
		}

		//reserve(ret.begin(),ret.end());
		//reverse(vec.begin(), vec.end()); //string没有反转函数,vector有
		
		//判断第一个非0位 //size_t startpos = sum.find_first_not_of("0");
		int flag = 0;
		for (int i = ret.size()-1; i >=0;i--)
		{
			if (ret[i]!='0')
			{
				flag = i;
				break;
			}
		}

		int begin = 0, end = flag;
		while (begin < end)
		{
			swap(ret[begin], ret[end]);
			begin++;
			end--;
		}

		return ret.substr(0,flag+1);
	}
};

题目来源

posted @ 2018-03-10 20:16  ranjiewen  阅读(139)  评论(0编辑  收藏  举报