image.png

思路

image.png

  1. public String addBinary(String a, String b) {
  2. StringBuilder ans = new StringBuilder();
  3. int carry = 0;
  4. for(int i=a.length()-1,j=b.length()-1;i>=0||j>=0;i--,j--){
  5. int sum = carry;
  6. sum += i>=0?a.charAt(i)-'0':0;
  7. sum += j>=0?b.charAt(j)-'0':0;
  8. ans.append(sum%2);
  9. carry=sum/2;
  10. }
  11. if(carry==1)
  12. ans.append(carry);
  13. return ans.reverse().toString();
  14. }