美文网首页
Multiply Strings go语言实现

Multiply Strings go语言实现

作者: fjxCode | 来源:发表于2018-09-22 15:34 被阅读0次

Multiply Strings

题目描述

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note: The numbers can be arbitrarily large and are non-negative.

思路:

  • 不需要逆序,正常计算。
  • 切片转为字串,Trim掉左边的0。单独处理空串,返回"0"

解:

package main

import (
    "fmt"
    "strings"
)

func multiply(num1 string, num2 string) string {
    bits := len(num1)+len(num2)+1
    resSlice := make([]rune,bits)
    for idx,_ := range resSlice {
        resSlice[idx] = '0'
    }
    num1Slice := []rune(num1)
    num2Slice := []rune(num2)

    for i:= len(num1Slice)-1;i>=0;i--{
        for j:= len(num2Slice)-1;j>=0 ; j-- {
            multiVal := (num1Slice[i]-48)*(num2Slice[j]-48)
            pos := i+j+2
            resSlice[pos-1] += (multiVal+resSlice[pos]-48)/10
            resSlice[pos] = (multiVal+resSlice[pos]-48)%10+48
        }
    }
    res := strings.TrimLeft(string(resSlice),"0")
    if res == "" {
        return "0"
    }
    return res
}

func main()  {
    res := multiply("123","456")
    fmt.Print(res)
}

相关文章

网友评论

      本文标题:Multiply Strings go语言实现

      本文链接:https://www.haomeiwen.com/subject/lxkxoftx.html