class Solution {
public String addBinary(String a, String b) {
int length_a = a.length();
int length_b = b.length();
String newBinary = "";
int flag = 0;
int num = 0;
while(length_a>0&&length_b>0){
num=(int)a.charAt(length_a-1)-'0'+(int)b.charAt(length_b-1)-'0'+flag;
newBinary=num%2+newBinary;
if(num>=2)flag = 1;
else flag = 0;
num =0;
length_a--;
length_b--;
}
while(length_a>0){
num=(int)a.charAt(length_a-1)-'0'+flag;
newBinary=num%2+newBinary;
if(num>=2)flag = 1;
else flag = 0;
num =0;
length_a--;
}
while(length_b>0){
num=(int)b.charAt(length_b-1)-'0'+flag;
newBinary=num%2+newBinary;
if(num>=2)flag = 1;
else flag = 0;
num =0;
length_b--;
}
if(flag==1)newBinary="1"+newBinary;
return newBinary;
}
}
网友评论