您的位置:首页 > 其它

Add Binary

2016-07-06 07:29 281 查看
public class Solution {
public String addBinary(String a, String b) {
if (a == null || b == null) {
throw new IllegalArgumentException("");
}
int i = a.length() - 1, j = b.length() - 1, carry = 0;
StringBuilder sb = new StringBuilder();
while (i >=0 || j >= 0 || carry != 0) {
int numA = 0;
if (i >= 0)
numA = a.charAt(i) - '0';
int numB = 0;
if (j >= 0)
numB = b.charAt(j) - '0';
int sum = (numA + numB + carry) % 2;
carry = (numA + numB + carry) / 2;
sb.insert(0, sum);
i--;
j--;
}
return sb.toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: