Add Binary

Given two binary strings, return their sum (also a binary string).

For example, a = "11" b = "1" Return "100".

Solution

public class Solution {

         public String addBinary(String a, String b) {
        int i= a.length() - 1, j = b.length() - 1;

        StringBuffer result = new StringBuffer();

        int adder = 0;
        int m, n;
        while (i > -1 && j > -1) {
            m = Integer.valueOf(a.charAt(i) - 48);
            n = Integer.valueOf(b.charAt(j) - 48);

            int temp = m + n + adder;
            adder = temp / 2;
            result.append(temp % 2);

            i --; j--;
        }


        if (i == -1) {
            while (j > -1) {

                int temp = adder + Integer.valueOf(b.charAt(j) - 48);
                adder = temp / 2;
                result.append(temp % 2);
                j --;
            }

        } else {

            while (i > -1) {

                int temp = adder + Integer.valueOf(a.charAt(i) - 48);
                adder = temp / 2;
                result.append(temp % 2);

                i --;
            }

        }

        if (adder != 0) {
            result.append(adder);
        }


        return result.reverse().toString();

    }
}

results matching ""

    No results matching ""