首页 > Web开发 > 详细

67. Add Binary(js)

时间:2019-03-11 20:51:43      阅读:204      评论:0      收藏:0      [点我收藏+]

67. 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"
题意:给定两个二进制数的字符串,求这两个二进制数相加,并返回求和数字的二进制
代码如下:
/**
 * @param {string} a
 * @param {string} b
 * @return {string}
 */
var addBinary = function(a, b) {
            var aLen=a.length-1;
        var bLen=b.length-1;
        var c=0;
        var s="";
        while(aLen >=0 || bLen >=0 || c===1){
            c+=aLen>=0 ? parseInt(a[aLen--]):0;
            c+=bLen>=0 ? parseInt(b[bLen--]):0;

            s=(c%2)+s;
            c=parseInt(c/2)
        }
        return s;
};

 

67. Add Binary(js)

原文:https://www.cnblogs.com/xingguozhiming/p/10512888.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!