leetcode-67. 二进制求和
leetcode
题目
https://leetcode-cn.com/problems/add-binary/
解法
题解中有三种方法,我用了模拟法,还算是比较简单
class Solution {
/**
* @param String $a
* @param String $b
* @return String
*/
function addBinary($a, $b) {
$lenA = strlen($a);
$lenB = strlen($b);
$ans = '';
$carry = 0;
for ($i = 0; $i < $lenA || $i < $lenB; $i++) {
$aBit = $lenA > $i ? $a[$lenA - $i - 1] : 0;
$bBit = $lenB > $i ? $b[$lenB - $i - 1] : 0;
$newBit = $carry + $aBit + $bBit;
$carry = floor($newBit / 2);
$newBit %= 2;
$ans = $newBit.$ans;
}
if ($carry > 0) {
$ans = $carry . $ans;
}
return $ans;
}
}
参考
本文来自博客园,作者:吴丹阳-V,转载请注明原文链接:https://www.cnblogs.com/wudanyang/p/14829237.html