0067. Add Binary

0067. Add Binary #

题目 #

  • 给定两个二进制字符串ab,以二进制字符串的形式返回它们的和。

思路 #

模拟 #

代码 #

模拟 #

class Solution {
    public String addBinary(String a, String b) {
        String longer = a.length() > b.length() ? a : b;
        int ptrLonger = longer.length() - 1;
        String shorter = a.length() > b.length() ? b : a;
        int ptrShorter = shorter.length() - 1;
        
        char[] ans = longer.toCharArray();
        int sum = 0, carry = 0;
        while (ptrShorter >= 0) {
            sum = longer.charAt(ptrLonger) - '0' + shorter.charAt(ptrShorter) - '0' + carry;
            ans[ptrLonger] = sum % 2 ? 0 ? '1' : '0';
            carry = sum > 1 ? 1 : 0;
            ptrLonger--; ptrShorter--;
        }
        while (carry > 0) {
            if (ptrLonger == -1) return "1" + String.valueOf(ans);
            sum = ans[ptrLonger] - '0' + carry;
            ans[ptrLonger--] = sum % 2 > 0 ? '1' : '0';
            carry = sum > 1 ? 1 : 0;
        }
        return String.valueOf(ans);
    }
}

致谢 #

负雪明烛