文章 217
评论 6
浏览 143928
String - 67. Add Binary

String - 67. Add Binary

  1. Add Binary

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"

思路:

题目是意思是实现二进制加法,给定两个二进制字符串,实现加法,做法就是用两个指针,从后往前遍历,把每一位加起来,满二进一。

代码:

go:

func addBinary(a string, b string) string {
    var (
        ap = len(a) - 1
        bp = len(b) - 1
        res = make([]byte, max(bp, ap) + 2)
        rp = len(res) - 1
    )
    
    for ap >= 0 || bp >= 0 {
        if ap >= 0 {
            res[rp] += (a[ap] - '0')
            if res[rp] > 1 {
                res[rp-1] = 1
                res[rp] = 0
            }
            ap--
        }
        
        if bp >= 0 {
            res[rp] += (b[bp] - '0')
            if res[rp] > 1 {
                res[rp-1] = 1
                res[rp] = 0
            }
            bp--
        }
        
        res[rp] += '0'
        rp--
    }
    // index 0 add '0'
    res[rp] += '0'
    
    if len(res) == 0 {
        return ""
    }
    
    if res[0] == '0' {
        res = res[1:]
    }
    return string(res)
}

func max(i, j int) int {
    if i > j {
        return i
    }
    return j
}


标题:String - 67. Add Binary
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2020/02/12/1581486140310.html

Nothing just happens, it's all part of a plan.

取消