For example,
a = "11"
b = "1"
Return "100".
Idea: Brute force. Keep adding from the ends of a and b until both a and b becomes empty and the carry is 0.
Time: O(n) Space: O(1)
Code:
public class Solution {
public String addBinary(String a, String b) {
StringBuilder builder=new StringBuilder();
int i=a.length()-1;
int j=b.length()-1;
int carry=0;
while(i>=0||j>=0||carry>0)
{
int valA=(i<0)?0:(int)(a.charAt(i)-'0');
int valB=(j<0)?0:(int)(b.charAt(j)-'0');
int sum=valA+valB+carry;
carry=sum/2;
sum=sum%2;
builder.insert(0,sum);
i--;
j--;
}
return builder.toString();
}
}
No comments:
Post a Comment