For example,
a =
"11"
b =
"1"
Return
"100"
.public class Solution {
public String addBinary(String a, String b) {
int maxLength = a.length()>b.length()?a.length()+1:b.length()+1;
int sum[] = new int[maxLength];
boolean add1 = false;
for(int i=1;i<=maxLength;i++) {
char c1 = '0';
char c2 = '0';
if(a.length()-i>=0) {
c1 = a.charAt(a.length()-i);
}
if(b.length()-i>=0) {
c2 = b.charAt(b.length()-i);
}
if(add1) {
sum[sum.length-i] = 1;
}
if(c1=='0'&&c2=='0') {
sum[sum.length-i] += 0;
}
if((c1=='1'&&c2=='0')||(c1=='0'&&c2=='1')) {
sum[sum.length-i] += 1;
}
if(c1=='1'&&c2=='1') {
sum[sum.length-i] += 2;
}
if(sum[sum.length-i]>1) {
sum[sum.length-i] %= 2;
add1 = true;
} else {
add1 = false;
}
}
if(add1) {
sum[0] = 1;
}
StringBuilder sb = new StringBuilder();
for(int i=0;i<sum.length;i++) {
if(i==0 && sum[i]==0) {
continue;
}
sb.append(sum[i]);
}
return sb.toString();
}
}
=======
public class Solution {
public String addBinary(String str1, String str2) {
StringBuilder sb = new StringBuilder();
int i1 = str1.length() - 1;
int i2 = str2.length() - 1;
int carry = 0;
int base = 2;
while (i1 >= 0 || i2 >= 0 || carry != 0) {
int val = carry;
val += i1 >= 0 ? (str1.charAt(i1) - '0') : 0;
val += i2 >= 0 ? (str2.charAt(i2) - '0') : 0;
carry = val / base;
sb.append(val % base);
i1--;
i2--;
}
return sb.reverse().toString();
}
}
没有评论:
发表评论