leet-code/multiply-strings/sol.go

37 lines
720 B
Go
Raw Normal View History

2021-11-07 20:58:43 +00:00
package main
// idk complexity
func multiply(num1 string, num2 string) string {
l1, l2 := len(num1), len(num2)
to_sum := make(map[int]int)
max_p10 := 0
for p1 := l1 - 1; p1 >= 0; p1-- {
for p2 := l2 - 1; p2 >= 0; p2-- {
n1, n2 := int(num1[p1])-48, int(num2[p2])-48
p10 := l1 - 1 - p1 + l2 - 1 - p2
d := n1 * n2
if p10 > max_p10 {
max_p10 = p10
}
to_sum[p10] = to_sum[p10] + d
}
}
sum := ""
for p := 0; p <= max_p10; p++ {
d := to_sum[p]
sum = string(48+(d%10)) + sum
to_sum[p+1] = to_sum[p+1] + d/10
if p+1 > max_p10 && d/10 > 0 {
max_p10 = p + 1
}
}
for len(sum) > 1 && sum[0] == '0' {
sum = sum[1:]
}
return sum
}
func main() {
println(multiply("123456", "0"))
}