415.字符串相加

时游小于 1 分钟LeetCode

415.字符串相加

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

// @lc code=start
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("");
	console.log(num1, num2);
	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(addStrings("1", "9"));
// @lc code=end

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