@@ -0,0 +1,1140 @@
+package com.pengyifan.leetcode;%0A%0A/**%0A * Given two binary strings, return their sum (also a binary string).%0A * %3Cp%3E%0A * For example,%0A * %3Cp%3E%0A * a = %2211%22%0A * %3Cp%3E%0A * b = %221%22%0A * %3Cp%3E%0A * Return %22100%22.%0A */%0Apublic class AddBinary %7B%0A  public String addBinary(String a, String b) %7B%0A    if (a.length() %3C b.length()) %7B%0A      String tmp = a;%0A      a = b;%0A      b = tmp;%0A    %7D%0A    String s = %22%22;%0A    int ai = a.length() - 1;%0A    int bi = b.length() - 1;%0A    boolean carry = false;%0A    while (bi %3E= 0) %7B%0A      char ac = a.charAt(ai);%0A      char bc = b.charAt(bi);%0A      if ((ac == '0' && bc == '1') %7C%7C (ac == '1' && bc == '0')) %7B%0A        s = (carry ? '0' : '1') + s;%0A      %7D else if ((ac == '0' && bc == '0')) %7B%0A        s = (carry ? '1' : '0') + s;%0A        carry = false;%0A      %7D else %7B%0A        s = (carry ? '1' : '0') + s;%0A        carry = true;%0A      %7D%0A      ai--;%0A      bi--;%0A    %7D%0A    while (ai %3E= 0) %7B%0A      char ac = a.charAt(ai);%0A      if (ac == '0') %7B%0A        s = (carry ? '1' : '0') + s;%0A        carry = false;%0A      %7D else %7B%0A        s = (carry ? '0' : '1') + s;%0A      %7D%0A      ai--;%0A    %7D%0A    if (carry) %7B%0A      s = '1' + s;%0A    %7D%0A    return s;%0A  %7D%0A%7D%0A

Add Binary