原题网址:https://www.lintcode.com/problem/add-binary/description
给定两个二进制字符串,返回他们的和(用二进制表示)。
a = 11
b = 1
返回 100
string addBinary(string &a, string &b)
{
int sizea=a.size();
int sizeb=b.size();
int i=sizea-1,j=sizeb-1;
int carry=0;
string result="";
while(i>=0||j>=0)
{
int p= i>=0?a[i--]-‘0‘:0;
int q= j>=0?b[j--]-‘0‘:0;
int sum=p+q+carry;
carry=sum/2;
sum=sum%2;
result+=(sum+‘0‘);
}
return carry==1?‘1‘+result:result;
}
class Solution {
public:
/**
* @param a: a number
* @param b: a number
* @return: the result
*/
string addBinary(string &a, string &b) {
// write your code here
int sizea=a.size();
int sizeb=b.size();
if (sizea==0)
{
return b;
}
if (sizeb==0)
{
return a;
}
int i=sizea-1,j=sizeb-1;
int carry=0;
string result="";
while(i>=0&&j>=0)
{
int sum=a[i]-‘0‘+b[j]-‘0‘+carry;
carry=sum/2;
sum=sum%2;
result+=(‘0‘+sum);
i--;
j--;
}
while(i>=0)
{
int sum=a[i]-‘0‘+carry;
carry=sum/2;
sum=sum%2;
result+=(‘0‘+sum);//int数字转char;
i--;
}
while(j>=0)
{
int sum=b[j]-‘0‘+carry;
carry=sum/2;
sum=sum%2;
result+=(‘0‘+sum);
j--;
}
if (carry==1)
{
result+=‘1‘;
}
reverse(result.begin(),result.end());
return result;
}
};
class Solution {
public:
/**
* @param a: a number
* @param b: a number
* @return: the result
*/
string addBinary(string &a, string &b) {
// write your code here
int sizea=a.size();
int sizeb=b.size();
if (sizea==0)
{
return b;
}
if (sizeb==0)
{
return a;
}
long long num1=0,num2=0;
for (int i=0;i<sizea;i++)
{
num1=num1+(a[i]-‘0‘)*pow(2.0,sizea-i-1);
}
for (int i=0;i<sizeb;i++)
{
num2=num2+(b[i]-‘0‘)*pow(2.0,sizeb-i-1);
}
num1=num1+num2;
if (num1==0)//此处判断不可少,否则a、b都为“0”时返回错误结果;
{
return "0";
}
string result="";
while(num1)
{
int tmp=num1%2;
if (tmp==0)
{
result=result+‘0‘;
}
else
{
result=result+‘1‘;
}
num1=num1/2;
}
reverse(result.begin(),result.end());
return result;
}
};
原文:https://www.cnblogs.com/Tang-tangt/p/9218923.html