您的位置:首页 > 其它

[LeetCode]Add Binary

2013-12-16 13:35 459 查看
Given two binary strings, return their sum (also a binary string).

For example,

a =
"11"


b =
"1"


Return
"100"
.

思考:大数相加的思想。

class Solution {
public:
string addBinary(string a, string b) {
if(a.length()==0) return b;
if(b.length()==0) return a;
int len=a.length()<b.length()?a.length():b.length();
if(len==a.length()) swap(a,b);
int len1=a.length();
int len2=b.length();
int i;
for(i=0;i<len;i++)
{
a[len1-1-i]=(a[len1-1-i]-'0')+(b[len2-1-i]-'0')+'0';
}
for(i=len1-1;i>0;i--)
{
if(a[i]>='2')
{
a[i]=(a[i]-'0')%2+'0';
a[i-1]=(a[i-1]-'0'+1)+'0';
}
}
if(a[0]>='2')
{
string ans(a,1,len1-1);
if(a[0]=='2') return "10"+ans;
else return "11"+ans;
}
else return a;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: