Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
a =
"11"b =
"1"Return
"100".[Thoughts]:
public class Solution {
public String addBinary(String a, String b) {
int carry = 0;
int p1 = a.length() - 1;
int p2 = b.length() - 1;
StringBuilder sb = new StringBuilder();
while(p1>=0 || p2>=0 || carry>0){
if(p1>=0)
carry += a.charAt(p1--)-'0';
if(p2 >=0)
carry += b.charAt(p2--)-'0';
sb.insert(0, carry%2);
carry = carry/2;
}
return sb.toString();
}
}
No comments:
Post a Comment