题目
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
示例 1:
输入: a = "11", b = "1"
输出: "100"
示例 2:
输入: a = "1010", b = "1011"
输出: "10101"
思路
- 将字符串转换成字符串数组
- 逢2进1
- char转化成int,要减48
代码
class Solution {
public String addBinary(String a, String b) {
int len1 = a.length(), len2 = b.length(),temp=0,sum=0;;
char[] c1 = a.toCharArray(), c2 = b.toCharArray();
String str = "";
int n=len1-1,m=len2-1,x,y;
while(n>=0 && m>=0){
x = c1[n]-48;
y = c2[m]-48;
sum = x+y+temp;
temp = sum/2;
str = sum%2+str;
n--;
m--;
}
while(n>=0){
x = c1[n]-48;
sum = x+temp;
temp = sum/2;
str = sum%2+str;
n--;
}
while(m>=0){
y = c2[m]-48;
sum = y+temp;
temp = sum/2;
str = sum%2+str;
m--;
}
if(temp>0) str = temp+str;
return str;
}
}