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`.
Input: a = "11", b = "1"
Output: "100"
Input: a = "1010", b = "1011"
Output: "10101"
/**
* @param {string} a
* @param {string} b
* @return {string}
*/
var addBinary = function (a, b) {
var aLength = a.length;
var bLength = b.length;
if (aLength < bLength) {
var dif = bLength - aLength;
var concatString = "";
while (dif) {
--dif;
concatString += "0";
}
a = concatString + a;
} else if (aLength > bLength) {
var dif = aLength - bLength;
var concatString = "";
while (dif) {
--dif;
concatString += "0";
}
b = concatString + b;
}
var length = a.length;
var result = '';
var rememeber = 0;
for (var i = length - 1; i >= 0; --i) {
var slug = ((+a[i]) + (+b[i]) + rememeber);
if (slug >= 2) {
slug = slug - 2;
rememeber = 1;
} else {
rememeber = 0;
}
result = slug + result;
}
if (rememeber === 1) {
result = "1" + result;
}
return result;
};
<?php
function addBinary(string $a, string $b): string
{
$aCount = strlen($a);
$bCount = strlen($b);
if ($aCount < $bCount) {
$diff = $bCount - $aCount;
$concatString = '';
while ($diff) {
$concatString = '0' . $concatString;
--$diff;
}
$a = $concatString . $a;
} elseif ($aCount > $bCount) {
$diff = $aCount - $bCount;
$concatString = '';
while ($diff) {
$concatString = '0' . $concatString;
--$diff;
}
$b = $concatString . $b;
}
$count = strlen($a);
$remember = 0;
$result = '';
for ($i = $count - 1; $i >= 0; --$i) {
$slug = $a[$i] + $b[$i] + $remember;
if ($slug >= 2) {
$slug = $slug - 2;
$remember = 1;
} else {
$remember = 0;
}
$result = $slug . $result;
}
if ($remember === 1) {
$result = '1' . $result;
}
return $result;
}
var_dump(addBinary('11','1'));