题目:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
题意:
给定两个二进制字符,返回他们的和
比如,
a = "11"
b = "1"
Return "100"
.
算法分析:
填充两个字符串中较短的,之后注意进位的问题,没什么特别的。
AC代码:
public class Solution
{
public String addBinary(String a, String b)
{
if(a.length()==0) return b;
if(b.length()==0) return a;
if(a.equals("0")) return b;
if(b.equals("0")) return a;
int i=0;
int j=0;
int newplus=0;
String res="";
String newa="";
String newb="";
String finalres="";
int maxlength;
maxlength=Math.max(a.length(), b.length());
//用‘0’填充a或者b,使其长度相等
if(a.length()>b.length())
{
for(i=0;i<a.length()-b.length();i++)
{
newb+='0';
}
for(i=0;i<b.length();i++)
newb+=b.charAt(i);
newa=a;
}
else if(b.length()>a.length())
{
for(i=0;i<b.length()-a.length();i++)
{
newa+='0';
}
for(i=0;i<a.length();i++)
newa+=a.charAt(i);
newb=b;
}
else
{
newa=a;
newb=b;
}
maxlength=Math.max(newa.length(), newb.length());
int plus=0;
int tem=0;
for(i=maxlength-1;i>=0;i--)
{
if(newa.charAt(i)=='1'&&newb.charAt(i)=='1')
{
tem=0+plus;
plus=1;
if(i==0)
{
newplus=1;
maxlength++;
}
}
else if(newa.charAt(i)=='0'&&newb.charAt(i)=='0')
{
tem=0+plus;
plus=0;
}
else
{
tem=1+plus;
if(tem==2)
{
tem=0;
plus=1;
if(i==0)
{
newplus=1;
maxlength++;
}
}
}
res+=Integer.toString(tem);
}
if(newplus==1) res=res+'1';
for(i=res.length()-1;i>=0;i--)
finalres+=res.charAt(i);
return finalres;
}
}