题目
给定两个二进制字符串,返回他们的和(用二进制表示)。
输入为非空字符串且只包含数字 1 和 0。
示例
示例 1:
输入: a = “11”, b = “1”
输出: “100”
示例 2:
输入: a = “1010”, b = “1011”
输出: “10101”
思路
这题其实从后往前遍历就行,只是需要在短的数字串前面补0,否则就会报错,注意进制的问题就行:
public String addBinary(String a, String b) {
StringBuilder newA=new StringBuilder(a);
StringBuilder newB=new StringBuilder(b);
StringBuilder temp=new StringBuilder();
int length=newA.length() > newB.length() ? newA.length() - newB.length():newB.length()-newA.length();
if (newA.length() > newB.length()){
while (length-- > 0){
newB.insert(0,"0");
}
}else {
while (length-- > 0){
newA.insert(0,"0");
}
}
// System.out.println(newA+" "+newB);
length=newA.length();
int flag=0;
for (int i=length-1; i >= 0;i--){
if(newA.charAt(i) == '0' && newB.charAt(i) == '1' || newA.charAt(i) == '1' && newB.charAt(i) == '0'){
if (flag == 1){
temp.insert(0,"0");
flag=1;
}else {
temp.insert(0,"1");
flag=0;
}
}else if(newA.charAt(i) == '0' && newB.charAt(i) == '0'){
if (flag == 1){
temp.insert(0,"1");
flag=0;
}else {
temp.insert(0,"0");
flag=0;
}
}else {
if (flag == 1){
temp.insert(0,"1");
flag=1;
}else {
temp.insert(0,"0");
flag=1;
}
}
}
if (flag == 1){
temp.insert(0,"1");
}
return temp.toString();
}