o0w0o / ARTS

ARTS 鸽友打卡🐦
2 stars 0 forks source link

Leetcode 43 #155

Open zwwhdls opened 4 years ago

zwwhdls commented 4 years ago

题意

给定两个字符串,输出其相乘结果,不可以直接将输入转成 Int。

思路

image

代码

func multiply(num1 string, num2 string) string {
    num1, num2 = "0"+num1, "0"+num2
    tmp := make([]byte, len(num1)+len(num2))
    for i := 0; i < len(tmp); i++ {
        tmp[i] = '0'
    }

    for i := 0; i < len(num1); i++ {
        p1 := len(num1) - i - 1
        ti := num1[p1]
        co := 0

        for j := 0; j < len(num2); j++ {
            p2 := len(num2) - j - 1
            tj := num2[p2]
            t := len(tmp) - 1 - i - j

            m := int(ti-'0')*int(tj-'0') + int(tmp[t]-'0') + co
            tmp[t] = byte(m%10 + '0')
            co = m / 10
        }
    }

    var b bytes.Buffer
    firstZero := true
    for i := 0; i < len(tmp); i++ {
        c := tmp[i]
        if firstZero && c == '0' {
            continue
        }
        firstZero = false
        b.WriteByte(c)
    }

    resStr := b.String()
    if resStr == "" {
        return "0"
    }
    return resStr
}