LeetCode 43 字符串相乘

给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。

注意:不能使用任何内置的 BigInteger 库或直接将输入转换为整数。

示例 1:

输入: num1 = "2", num2 = "3"
输出: "6"

示例 2:

输入: num1 = "123", num2 = "456"
输出: "56088"

提示:

  • 1 <= num1.length, num2.length <= 200
  • num1 和 num2 只能由数字组成。
  • num1 和 num2 都不包含任何前导零,除了数字0本身。

解题:

按照竖式乘法分开来计算后加起来

func multiply(num1 string, num2 string) string {
	if num1 == "0" || num2 == "0" {
		return "0"
	}
	l := len(num2)
	strNum := make([]string, 0)
	s := ""
	for i := l - 1; i >= 0; i-- {
		str := strMulti(num1, num2[i]) + s
		strNum = append(strNum, str)
		s += "0"
	}
	s = "0"
	for _, v := range strNum {
		s = strAdd(s, v)
	}
	return s
}

func strMulti(num1 string, num uint8) string {
	if num == '0' {
		return "0"
	}
	s := ""
	l := len(num1)
	var a uint8 = 0
	num -= '0'
	for i := l - 1; i >= 0; i-- {
		s = strconv.Itoa(int(((num1[i]-'0')*num+a)%10)) + s
		a = ((num1[i]-'0')*num + a) / 10
	}
	if a > 0 {
		s = strconv.Itoa(int(a)) + s
	}
	return s
}

func strAdd(a, b string) string {
	if b == "0" {
		return a
	}
	l := len(b)
	if l > len(a) {
		l = len(a)
		a, b = b, a
	}
	var c uint8 = 0
	s := ""
	for i, j := len(a)-1, l-1; i >= 0; i-- {
		if j >= 0 {
			s = strconv.Itoa(int(a[i]+b[j]-2*'0'+c)%10) + s
			c = (a[i] + b[j] - 2*'0' + c) / 10
		} else {
			s = strconv.Itoa(int(a[i]-'0'+c)%10) + s
			c = (a[i] - '0' + c) / 10
		}
		j--
	}
	if c > 0 {
		s = strconv.Itoa(int(c)) + s
	}
	return s
}

官方解答:

1.做加法

func multiply(num1 string, num2 string) string {
	if num1 == "0" || num2 == "0" {
		return "0"
	}
	ans := "0"
	m, n := len(num1), len(num2)
	for i := n - 1; i >= 0; i-- {
		curr := ""
		add := 0
		for j := n - 1; j > i; j-- {
			curr += "0"
		}
		y := int(num2[i] - '0')
		for j := m - 1; j >= 0; j-- {
			x := int(num1[j] - '0')
			product := x*y + add
			curr = strconv.Itoa(product%10) + curr
			add = product / 10
		}
		for ; add != 0; add /= 10 {
			curr = strconv.Itoa(add%10) + curr
		}
		ans = addStrings(ans, curr)
	}
	return ans
}

func addStrings(num1, num2 string) string {
	i, j := len(num1)-1, len(num2)-1
	add := 0
	ans := ""
	for ; i >= 0 || j >= 0 || add != 0; i, j = i-1, j-1 {
		x, y := 0, 0
		if i >= 0 {
			x = int(num1[i] - '0')
		}
		if j >= 0 {
			y = int(num2[j] - '0')
		}
		result := x + y + add
		ans = strconv.Itoa(result%10) + ans
		add = result / 10
	}
	return ans
}

2.做乘法

func multiply(num1 string, num2 string) string {
	if num1 == "0" || num2 == "0" {
		return "0"
	}
	m, n := len(num1), len(num2)
	ansArr := make([]int, m+n)
	for i := m - 1; i >= 0; i-- {
		x := int(num1[i]) - '0'
		for j := n - 1; j >= 0; j-- {
			y := int(num2[j] - '0')
			ansArr[i+j+1] += x * y
		}
	}
	for i := m + n - 1; i > 0; i-- {
		ansArr[i-1] += ansArr[i] / 10
		ansArr[i] %= 10
	}
	ans := ""
	idx := 0
	if ansArr[0] == 0 {
		idx = 1
	}
	for ; idx < m+n; idx++ {
		ans += strconv.Itoa(ansArr[idx])
	}
	return ans
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注