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;
    }
}

参考

posted @ 2021-05-30 21:36  吴丹阳-V  阅读(35)  评论(0编辑  收藏  举报