congr / world

2 stars 1 forks source link

LeetCode : 67. Add Binary #489

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/add-binary/

image

congr commented 5 years ago
class Solution {
    public String addBinary(String a, String b) {
        int sum = 0, carry = 0;
        int p = a.length()-1, q = b.length()-1;

        StringBuilder sb = new StringBuilder();
        while (p >= 0 || q >= 0) { // p-- q-- don't do here.
            sum = carry;
            if (p >= 0) sum += a.charAt(p) - '0';
            if (q >= 0) sum += b.charAt(q) - '0';

            carry = sum / 2;   // !!!
            sb.append(sum % 2);// !!!
            p--; q--;
        }

        if (carry == 1) sb.append(1);

        return sb.reverse().toString();
    }
}