LeetCode Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
1 public class Solution { 2 public String addBinary(String a, String b) { 3 4 int la=a.length(); 5 int lb=b.length(); 6 char[] chars=new char[Math.max(la,lb)+1]; 7 int flag=0; 8 int lastA=la-1; 9 int lastB=lb-1; 10 int c=0; 11 int currA,currB; 12 for (int i = chars.length-1; i >=0; i--) { 13 currA=lastA>=0?a.charAt(lastA):'0'; 14 currB=lastB>=0?b.charAt(lastB):'0'; 15 c=currA-'0'+currB-'0'+flag; 16 if (c==3) { 17 chars[i]='1'; 18 flag=1; 19 }else if (c==2) { 20 chars[i]='0'; 21 flag=1; 22 }else { 23 chars[i]=(char) ('0'+c); 24 flag=0; 25 } 26 lastA--; 27 lastB--; 28 } 29 String string=new String(chars); 30 if (string.charAt(0)=='0') { 31 return string.substring(1); 32 } 33 return string; 34 } 35 }