美文网首页
leetcode:67. Add Binary

leetcode:67. Add Binary

作者: 唐僧取经 | 来源:发表于2018-08-26 22:32 被阅读0次

67. Add Binary

Description

Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"
Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

Answer

package main

import "fmt"

//96:0+0,97:0+1;98:1+1
func addBinary(a string, b string) string {
    la := len(a)
    lb := len(b)
    if lb > la { //守住a为最长的
        tmp := a
        a = b
        b = tmp
        la = len(a)
        lb = len(b)
    }

    if la > lb { //补齐两个字符串的长度,前面补齐0
        for i := la - lb; i > 0; i-- {
            b = "0" + b
        }
    }
    plus := 0
    res := ""
    for i := la - 1; i != -1; i-- { //从后往前
        ans := int(a[i]) + int(b[i]) + plus //利用算数特征

        if ans >= 98 {
            res = string(ans-'2') + res
            plus = 1
        } else {
            res = string(ans-'0') + res
            plus = 0
        }
    }
    if plus == 1 {
        res = "1" + res
    }
    return res

}
func main() {
    fmt.Println(addBinary("11", "1111"))
}


相关文章

网友评论

      本文标题:leetcode:67. Add Binary

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