Total Accepted: 40264 Total Submissions: 161822My Submissions
Question Solution
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
分析,模拟二进制,一位一位的运算,从后往前,两个字符串一块进行,一定要注意“进位”的处理
public class Solution {
public String addBinary(String a, String b) {
int la=a.length();
int lb=b.length();
int jinwei=0;
int ca=la-1;
int cb=lb-1;
String oc="";
while(ca>=0&&cb>=0)
{
int x=a.charAt(ca)-‘0‘;
int y=b.charAt(cb)-‘0‘;
if(x==0)
{
x=x+jinwei;
jinwei=0;
}
else if(y==0)
{
y=y+jinwei;
jinwei=0;
}
else
{
if(jinwei>0)
{
x=0;
y=1;
jinwei=1;
}
}
if(x==0&&y==0)
oc=String.valueOf(0)+oc;
else if(x==0||y==0)
oc=String.valueOf(1)+oc;
else
{
oc=String.valueOf(0)+oc;
jinwei=1;
}
ca--;
cb--;
}
if(ca==-1&&cb!=-1)
{
while(cb>=0)
{
if(jinwei==0)
{
oc=String.valueOf(b.charAt(cb))+oc;
cb--;
}
else
{
if(b.charAt(cb)==‘1‘)
{
oc=String.valueOf(0)+oc;
jinwei=1;
}
else
{
oc=String.valueOf(1)+oc;
jinwei=0;
}
cb--;
}
}
}
else if(ca!=-1&&cb==-1)
{
while(ca>=0)
{
if(jinwei==0)
{
oc=String.valueOf(a.charAt(ca))+oc;
ca--;
}
else
{
if(a.charAt(ca)==‘1‘)
{
oc=String.valueOf(0)+oc;
jinwei=1;
}
else
{
oc=String.valueOf(1)+oc;
jinwei=0;
}
ca--;
}
}
}
if(jinwei==1)
oc=String.valueOf(1)+oc;
return oc;
}
}