您的位置:首页 > 其它

lintcode ----二进制求和

2016-05-20 16:50 211 查看
想法:先转化为整数,相加后,转为二进制数

string addBinary(string& a, string& b)
{
// Write your code here
if(a=="0"&&b=="0")
return "0";
string res="";
int na=0,nb=0;
int la=a.length();
int lb=b.length();
for(int i=0;i<a.length();i++)
{
la--;
if(a[i]=='1')
{
na+=pow(double(2),la);
}

}
for(int i=0;i<b.length();i++)
{
lb--;
if(b[i]=='1')
{
nb+=pow(double(2),lb);
}

}
int add=na+nb;
while(add)
{
int tem=add%2;
res+=to_string(tem);
add/=2;
}
reverse(res.begin(),res.end());
return res;

}
PS:我记得之前有个类似的题目,这样写会溢出,欢迎大家亲喷指点!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: