【LeetCode】【esay】【67】二進制求和

給你兩個二進制字符串,返回它們的和(用二進制表示)。

輸入爲 非空 字符串且只包含數字 1 和 0

 

示例 1:

輸入: a = "11", b = "1"
輸出: "100"

示例 2:

輸入: a = "1010", b = "1011"
輸出: "10101"

 

提示:

  • 每個字符串僅由字符 '0' 或 '1' 組成。
  • 1 <= a.length, b.length <= 10^4
  • 字符串如果不是 "0" ,就都不含前導零。
var test = function(c){
    // return Array.prototype.reverse.call(c.split("").toString().replace(/,/g,""));
    
    return c.split("").reverse();
}

/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
var addBinary = function(a, b) {
    // // return parseInt(a,2)+parseInt(b,2);
    // // return parseInt((parseInt(a,2)+parseInt(b,2).toString()),2).toString();
    // let aa = (parseInt(a,2)+parseInt(b,2)).toString(2);
    // // console.log(aa+"");
    // // console.log(parseInt(aa+"",2));
    // return aa;
    // a = "101";
    // let aR = Array.prototype.reverse.call(a.split(""));
    // console.log(aR.toString().replace(/,/g,""));
    let aR = test(a);
    let bR = test(b);
    // console.log(aR,bR);

    let rs = new Array();
    let flg = false;
    let i=0;
    for(;i < aR.length && i<bR.length ;i++){

        if(flg){

            if(aR[i]==0&&bR[i]==0){
                rs.push(1);
                flg = false;
            }else if((aR[i]==1&&bR[i]==0)||(aR[i]==0&&bR[i]==1)){
                rs.push(0);
                flg = true;
            }else{
                rs.push(1);
                flg = true;
            }
        }else{

            if(aR[i]==0&&bR[i]==0){
                rs.push(0);
            }else if((aR[i]==1&&bR[i]==0)||(aR[i]==0&&bR[i]==1)){
                rs.push(1);
            }else{
                rs.push(0);
                flg = true;
            }
        }
    }

    // console.log(i);
    // i--;
    // console.log(rs);
    if(i<aR.length){
        for(let j=i;j<aR.length;j++){
            // console.log(j);
            if(flg){

                if(aR[j]==0){

                    rs.push(1);
                    flg = false;
                }else{
                    rs.push(0);
                    flg = true;
                }
            }else{
                rs.push(aR[j]);
            }
        }
    }

    if(i<bR.length){
        for(let k=i;k<bR.length;k++){

            if(flg){

                if(bR[k]==0){

                    rs.push(1);
                    flg = false;
                }else{
                    rs.push(0);
                    flg = true;
                }
            }else{
                rs.push(bR[k]);
            }
        }
    }

    if(flg){
        rs.push(1);
    }

    return rs.reverse().toString().replace(/,/g,"");

};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章