Title: Given two binary string, and return to their (expressed in binary). And a non-empty input string contains only numbers 0 and 1.
An idea: the two strings turn into an integer, are added, then the obtained and converted to binary. But there is a long string exceeds the limit.
classSolution{public String addBinary(String a, String b){int aa = Integer.parseInt(a);int bb = Integer.parseInt(b);int sum = aa+bb;
String ans ="";if(sum ==0)return"0";while(sum>0){int k=sum%10;if(k <2){
sum=sum/10;
ans+=k;}else{
sum=sum/10+1;
k=k-2;
ans+=k;}}returnnewStringBuilder(ans).reverse().toString();}}
Ideas II: From the start of the last string judge.
classSolution{public String addBinary(String a, String b){int lenA = a.length();int lenB = b.length();int aa = lenA-1;int bb = lenB-1;
String ans ="";
String next ="0";while(aa>=0&& bb>=0){if(a.charAt(aa)=='1'&& b.charAt(bb)=='1'){
ans+=next;
next="1";}elseif(a.charAt(aa)=='1'|| b.charAt(bb)=='1'){if(next=="1"){
ans+="0";
next="1";}else{
ans+="1";
next="0";}}else{
ans+=next;
next="0";}
aa--;
bb--;}if(aa>=0){while(aa>=0){if(next=="1"){if(a.charAt(aa)=='0'){
ans+="1";
next="0";}else{
ans+="0";
next="1";}}else{
ans+=a.charAt(aa);}
aa--;}}elseif(bb>=0){while(bb>=0){if(next=="1"){if(b.charAt(bb)=='0'){
ans+="1";
next="0";}else{
ans+="0";
next="1";}}else{
ans+=b.charAt(bb);}
bb--;}}if(next=="1") ans+="1";returnnewStringBuilder(ans).reverse().toString();}}
Thinking three: problem solution in the short string padded with zeros, I saved half of the code.
classSolution{public String addBinary(String a, String b){
StringBuilder ans =newStringBuilder();int ca =0;for(int i = a.length()-1, j = b.length()-1;i >=0|| j >=0; i--, j--){int sum = ca;
sum += i >=0? a.charAt(i)-'0':0;
sum += j >=0? b.charAt(j)-'0':0;
ans.append(sum %2);
ca = sum /2;}
ans.append(ca ==1? ca :"");return ans.reverse().toString();}}
作者:guanpengchn
链接:https://leetcode-cn.com/problems/add-binary/solution/hua-jie-suan-fa-67-er-jin-zhi-qiu-he-by-guanpengch/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。