@@ -0,0 +1,1718 @@
+/*%0A * Key point: add a %220%22 to the beginning of a and b%0A *   so that there will be no carry to increase length%0A *   then, add %220%22 to the shorter string until a and b%0A *   are of same length%0A *   finally check whether the first char of result is %220%22%0A *   if so, trim it before return%0A */%0A%0Apublic class Solution %7B%0A    public String addBinary(String a, String b) %7B%0A        if(a == null && b == null)%0A            return null;%0A            %0A        if(a != null && (b == null %7C%7C b.length() == 0))%0A            return a;%0A            %0A        if(b != null && (a == null %7C%7C a.length() == 0))%0A            return b;%0A        %0A        //make string a is the shorter one%0A        if(a.length() %3E b.length())%7B%0A            String temp = a;%0A            a = b;%0A            b = temp;%0A        %7D%0A%0A        //add 0 to the beginning of a and b%0A        a = %220%22+a;%0A        b = %220%22+b;%0A%0A        StringBuffer sb = new StringBuffer();%0A        for(int i = b.length() - a.length(); i %3E 0;i--)%7B%0A            sb.insert(0,'0');%0A        %7D%0A%0A        //using %220%22 to make a and b of same length%0A        a = sb.toString()+a;%0A        %0A        int bit = 0;%0A        int carry = 0;%0A        int tempSum = 0;%0A        sb.setLength(0);    //clear StringBuffer sb%0A        %0A        for(int i = 0;i %3C a.length();i++)%7B%0A            tempSum = carry + (int) (a.charAt(a.length() - 1 - i) - '0') + (int) (b.charAt(b.length() - 1 - i) - '0');%0A            bit = tempSum %25 2;%0A            carry = tempSum / 2;%0A            sb.insert(0, (char) ('0' + bit));%0A        %7D%0A        %0A        //if the first char of result isn't 1, remove it%0A        if(sb.charAt(0) == '0')%7B%0A                return sb.substring(1);%0A        %7D%0A        else%0A            return sb.toString();     %0A        %0A    %7D%0A%7D

Add Binary