Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
a =
"11"
b =
"1"
Return
"100"
.
Answer:
//Traverse from tail to head:
public class Solution {
public String addBinary(String a, String b) {
int len1 = a.length();
int len2 = b.length();
if(a==null || len1==0)return b;
if(b==null || len2==0)return a;
int pa = len1-1;
int pb = len2-1;
int flag = 0;
StringBuilder sb = new StringBuilder();
while(pa >= 0 || pb >= 0){
//reset every time!
int va = 0;
int vb = 0;
if(pa >= 0){
va = Integer.parseInt("" + a.charAt(pa));
pa--;
}
if(pb >= 0){
vb = Integer.parseInt("" + b.charAt(pb));
pb--;
}
int sum = va + vb + flag;
if(sum >= 2){
flag = 1;
sb.insert(0, sum-2);
}else{
flag = 0;
sb.insert(0, sum);
}
}
if(flag==1){
sb.insert(0, 1);
}
return sb.toString();
}
}
No comments:
Post a Comment