67. Add Binary

class Solution {

    /**
     * @param String $a
     * @param String $b
     * @return String
     */
    function addBinary($a, $b) {
        if ($a == 0 || $b == 0){
            return (string)($a + $b);
        }

        $binaryA = str_split($a);
        $binaryB = str_split($b);
        $times = max(strlen($a), strlen($b));
        $result = '';
        $next = 0;
        while($times > 0) {
            --$times;
            $lastA = array_pop($binaryA);
            $lastB = array_pop($binaryB);
            $current = $lastA + $lastB + $next;
            if ($current == 3) {
                $next = 1;
                $current = 1;
            } elseif ($current == 2){
                $next = 1;
                $current = 0;
            } else {
                $next = 0;
            }
            $result =  (string)$current.$result;
        }

        return $next == 1
        ? $next.$result
        : $result;
    }
}

Last updated