您的位置:首页 > 其它

67. Add Binary

2016-04-07 21:31 337 查看
Given two binary strings, return their sum (also a binary string).

For example,
a =
"11"

b =
"1"

Return
"100"
.

public class Solution {
public String addBinary(String a, String b) {
if (a == null || a == "")
return b;
if (b == null || b == "")
return a;
int carry = 0;
String ret = "";
int l1 = a.length()-1;
int l2 = b.length()-1;
while (l1 >= 0 || l2 >= 0 || carry == 1) {
if (l1 >= 0) {
carry += Integer.parseInt(a.charAt(l1)+"");
l1--;
}
if (l2 >= 0) {
carry += Integer.parseInt(b.charAt(l2)+"");
l2--;
}
ret = String.valueOf(carry%2) + ret;
carry /= 2;
}
return ret;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: