美文网首页
Valid Number go语言实现

Valid Number go语言实现

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

    Valid Number

    题目描述

    Given two binary strings, return their sum (also a binary string).
    For example,
    a ="11"
    b ="1"
    Return"100"
    

    思路:

    • 字串先对齐,再相加,再进。

    细节:

    • 用字节数组处理字串。

    解:

    package main
    
    import "fmt"
    
    func addBinary(a string, b string) string {
        var maxLen int
        switch len(a) > len(b) {
        case true:
            maxLen = len(a)
        case false:
            maxLen = len(b)
        }
    
        aByte := make([]byte,maxLen+1)
        for idx,_ := range aByte {
            aByte[idx] = 48
        }
        bByte := make([]byte,maxLen+1)
        for idx,_ := range bByte{
            bByte[idx] = 48
        }
        for i := 0; i < len(a); i++ {
            aByte[i+maxLen-len(a)+1] = a[i]
        }
        for i := 0; i < len(b); i++ {
            bByte[i+maxLen-len(b)+1] = b[i]
        }
        preString := make([]byte,maxLen+1)
        for i := 0; i < maxLen+1; i++ {
            preString[i] = aByte[i]+bByte[i]- 48
        }
        for i := maxLen; i > 0; i-- {
            if preString[i] == 50 {
                preString[i] = 48
                preString[i-1] = preString[i-1]+1
    
            }else if preString[i] == 51 {
                preString[i] = 49
                preString[i-1] = preString[i-1]+1
            }
        }
        if preString[0] == 49 {
            return string(preString)
        }
        return string(preString[1:])
    }
    
    
    func main()  {
        a := "11"
        b := "1"
        fmt.Print(addBinary(a,b))
    }
    

    相关文章

      网友评论

          本文标题:Valid Number go语言实现

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