Given two binary strings, return their sum (also a binary string).
For example, a = “11” b = “1” Return “100”.
主要处理好进位的问题,PHP实现代码如下:
function BinaryAdd($num1, $num2) {
$last_index_1 = strlen($num1) - 1;
$last_index_2 = strlen($num2) - 1;
// 是否进位
$flag = 0;
$binary = '';
while ($last_index_1 >= 0 || $last_index_2 >= 0) {
$binary1 = $last_index_1 < 0 ? 0 : $num1[$last_index_1];
$binary2 = $last_index_2 < 0 ? 0 : $num2[$last_index_2];
$sum = $binary1 + $binary2 + $flag;
// 判断是否需要进位 和为2或者3时需要进位
switch ($sum) {
case 2:
$flag = 1;
$binary = '0' . $binary;
break;
case 3:
$flag = 1;
$binary = '1' . $binary;
break;
default:
$binary = $sum . $binary;
$flag = 0;
break;
}
$last_index_1--;
$last_index_2--;
}
// 如果有进位,则首位补1
if ($flag == 1) $binary = '1' . $binary;
return $binary;
}
echo BinaryAdd('11', '1');