C++ ,leetcode 43. 字符串相乘 給定兩個以字符串形式表示的非負整數 num1 和 num2,返回 num1 和 num2 的乘積,它們的乘積也表示爲字符串形式

一、思路:

      字符串逆序,然後遍歷兩個逆序後的字符串,然後對應的字符相乘,i+j等於它的位數。

string multiply(string num1, string num2) {
	reverseStr(num1);
	reverseStr(num2);
	string res;
	int carry = 0;
	for (int i = 0; i < num1.size(); i++) {
		carry = 0;
		for (int j = 0; j < num2.size(); j++) {
			int temp = (num1[i] - '0')*(num2[j] - '0') + carry;
			if (i + j >= res.size()) {
				res.push_back(temp % 10 + '0');
				carry = temp / 10;
			}
			else {
				int temp1 = res[i + j] + temp - '0';
				res[i + j] = temp1 % 10 + '0';
				carry = temp1 / 10;
			}
			if (carry != 0 && j == num2.size() - 1)
				res.push_back(carry + '0');
		}
	}

	while (res.back() == '0' && res.size() > 1) {
		res.pop_back();
	}
	reverseStr(res);
	return res;
}

void reverseStr(string &num)
{
	for (int i = 0; i < num.size() / 2; i++) {
		char ch = num[i];
		num[i] = num[num.size() - i - 1];
		num[num.size() - i - 1] = ch;
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章