您的位置:首页 > 其它

67.LeetCode Add Binary(easy)[字符串 大数相加处理]

2016-04-14 17:04 465 查看
Given two binary strings, return their sum (also a binary string).

For example,

a = 
"11"


b = 
"1"


Return 
"100"
.

这个题是要实现对字符串完成二进制加法的功能,类似于大数加法这样的功能,需要考虑的是进位位、两个串不是一样长的时候需要补0的操作。这个题需要实现1+1 进位这样的规则设定。(要点:补0,进位处理)

具体思路如下:首先获取两个字符串的长度,对较短的字符串的前面添加‘0’字符,然后从数组的末尾开始相加,每次相加时注意修改进位标志,最后返回结果字符串。

class Solution {
public:
string addBinary(string a, string b) {
int len1 = a.length();
int len2 = b.length();
if(len1>len2)
{
int t = len1-len2;
while(t--)
{
b = "0"+b;
}
}else if(len1<len2)
{
int t = len2-len1;
while(t--)
{
a = "0"+a;
}
}

string c;
char flag = '0';
//cout<<a<<" "<<b<<endl;
for(int i=a.length()-1;i>=0;i--)
{
if(a[i]=='1'&&b[i]=='1')
{
c = flag + c;
flag = '1';
}else if((a[i]=='1'&&b[i]=='0')||(a[i]=='0'&&b[i]=='1'))
{
if(flag == '0')
{
c = '1'+c;
}else{
c = '0'+c;
}
}else {
c = flag + c;
flag = '0';
}
}
//cout<<flag<<endl;
if(flag == '1')
c = flag + c;
return c;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: