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; };
原文:https://www.cnblogs.com/xingguozhiming/p/10512888.html