[Leetcode] Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Solution:
1 public class Solution { 2 public String addBinary(String a, String b) { 3 if(a==null) 4 return b; 5 if(b==null) 6 return a; 7 int end_a=a.length()-1; 8 int end_b=b.length()-1; 9 int carry=0; 10 String result=""; 11 while(end_a>=0&&end_b>=0){ 12 int temp=(a.charAt(end_a)-'0')+(b.charAt(end_b)-'0')+carry; 13 carry=temp/2; 14 temp%=2; 15 result=(temp+"")+result; 16 end_a--; 17 end_b--; 18 } 19 while(end_a>=0){ 20 int temp=(a.charAt(end_a)-'0')+carry; 21 carry=temp/2; 22 temp%=2; 23 result=(temp+"")+result; 24 end_a--; 25 } 26 while(end_b>=0){ 27 int temp=(b.charAt(end_b)-'0')+carry; 28 carry=temp/2; 29 temp%=2; 30 result=(temp+"")+result; 31 end_b--; 32 } 33 if(carry!=0){ 34 result=(carry+"")+result; 35 } 36 return result; 37 } 38 }