43.字符串相乘

时游小于 1 分钟LeetCode

43.字符串相乘

/*
 * @lc app=leetcode.cn id=43 lang=typescript
 *
 * [43] 字符串相乘
 */

// @lc code=start
function multiply(num1: string, num2: string): string {
	let result: string = "";
	let l = 0;
	if (Number(num1) + Number(num2) == 0) return "0";

	let min = Math.min(num1.length, num2.length);
	let minStr = min === num1.length ? num1 : num2;
	let maxStr = min === num1.length ? num2 : num1;

	for (let i = min - 1; i >= 0; i--) {
		// 将较小字符串倒着乘较长字符串每一项
		let currentRes: string[] = [];
		for (let j = maxStr.length - 1; j >= 0; j--) {
			let sum =
				Number(currentRes[j] ?? 0) +
				Number(maxStr[j] ?? 0) * Number(minStr[i] ?? 0);

			if (sum >= 10) {
				currentRes[j] = `${String(sum)[1]}`;
				if (j == 0) {
					currentRes.unshift(`${String(sum)[0]}`);
				} else {
					currentRes[j - 1] = `${String(sum)[0]}`;
				}
			} else {
				currentRes[j] = `${String(sum)}`;
			}
		}
		for (let zero = i; zero < min - 1; zero++) {
			currentRes.push("0");
		}
		// 相加
		result = addStrings(result, currentRes.join(""));
	}

	return result;
}

// 字符串相加
function addStrings(num1: string, num2: string): string {
	let result: string[] = [];
	let l = 0;
	if (Number(num1) + Number(num2) == 0) return "0";

	// 反转num1 num2
	num1 = num1.split("").reverse().join("");
	num2 = num2.split("").reverse().join("");
	let max = Math.max(num1.length, num2.length);
	while (l <= max - 1) {
		let sum =
			Number(num1[l] ?? 0) +
			Number(num2[l] ?? 0) +
			Number(result[l] ?? 0);
		if (sum >= 10) {
			result[l + 1] = "1"; // 前两位相加超过10
			result[l] = String(sum - 10);
		} else {
			// 和小于10
			result[l] = String(sum);
		}

		l++;
	}

	return result.reverse().join("");
}

console.log(multiply("123", "456"));

// @lc code=end

上次编辑于:
贡献者: 15327360835
Loading...