给定两个二进制字符串,返回它们的和(也是一个二进制字符串)。
举例:
a = "11"
b = "1"
返回 "100".
解题思路:
- 这题比较简单,所以我使用的是比较暴力的算法
- 将两个字符串转换成整型数组的形式
- 对两个数组进行相加,注意进位
- 将求得的和数组转换成字符串返回
代码如下:
public String addBinary(String a, String b) {
int len1 = a.length();
int len2 = b.length();
int maxlen = len1 > len2 ? len1 : len2;
int [] m = new int [maxlen ];
int [] n = new int [maxlen ];
// 将字符串转换成数组
int index1 = 0;
while(len1 < maxlen){
m[index1++] = 0;
len1++;
}
for(int i = 0; i < a.length(); i++){
m[index1++] = (int)(a.charAt(i) - 48);
}
int index2 = 0;
while(len2 < maxlen){
n[index2++] = 0;
len2++;
}
for(int i = 0; i < b.length(); i++){
n[index2++] = (int)(b.charAt(i) - 48);
}
return add(m,n);
}
// 对数组进行求和
private String add(int [] m, int [] n){
int [] res = new int [m.length + 1];
int index = res.length - 1;
int count = 0;
for(int i = m.length - 1; i >= 0; i--){
count += m[i] + n[i];
// 利用 count 处理进位
if(count == 0){
res[index--] = 0;
count = 0;
}
else if(count == 1){
res[index--] = 1;
count = 0;
}
else if(count == 2){
res[index--] = 0;
count = 1;
}
else if(count == 3){
res[index--] = 1;
count = 1;
}
}
// 处理和数组的第一位问题
if(count == 1){
res[index] = count;
}else{
res = Arrays.copyOfRange(res,1,res.length);
}
// 将数组转换为字符串,并返回
String rs = "";
for(int i = 0; i < res.length; i++){
rs += res[i];
}
return rs;
}