Skip to content

Latest commit

 

History

History
executable file
·
65 lines (49 loc) · 1.26 KB

0067._Add_Binary.md

File metadata and controls

executable file
·
65 lines (49 loc) · 1.26 KB

67. Add Binary

难度: Easy

刷题内容

原题连接

内容描述

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"

解题方案

思路 1 - 时间复杂度: O(N)- 空间复杂度: O(N)******

  • 对于每一位数进行加法,如有进位单独计算
  • 注意需使用字符串进行存储,整型无法计算大型数据

代码:

/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
var addBinary = function(a, b) {
    var tempA = a.split('');
    var tempB = b.split('');
    var result =[];
    var aLen=tempA.length,bLen=tempB.length;
    var carry = 0;
    while(aLen>0||bLen>0){
        var charA=0,charB=0;
        if(aLen>0)
            charA = tempA[--aLen]-0;
        if(bLen>0)
            charB = tempB[--bLen]-0;
        var temp = charA + charB + carry;
        carry = temp>1?1:0;
        result.unshift(temp%2);
    }
    if(carry===1)
        result.unshift(1);
    return result.toString().replace(/,/g,'');
};