Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
solution:
Basic implementation question.
Starts from the end of String. Be care of empty String case.
Tips: use StringBuilder, its append is faster than String1 + String2. Also, it has .reverse().
a =
"11"b =
"1"Return
"100".solution:
Basic implementation question.
Starts from the end of String. Be care of empty String case.
Tips: use StringBuilder, its append is faster than String1 + String2. Also, it has .reverse().
public class Solution {
public String addBinary(String a, String b) {
StringBuilder str = new StringBuilder();
int carry = 0;
int i = a.length() - 1;
int j = b.length() - 1;
while(i >= 0 || j >= 0){
int num_a = 0, num_b = 0;
num_a = i >= 0 ? (a.charAt(i)-'0') : 0;
num_b = j >= 0 ? (b.charAt(j)-'0') : 0;
int tmp = carry + num_a + num_b;
carry = tmp / 2;
str.append(tmp % 2);
j--;
i--;
}
if(carry == 1) str.append(carry);
str.reverse();
return str.toString();
}
}
No comments:
Post a Comment