Leetcode 67 Add Binary
来源:程序员人生 发布时间:2016-11-10 09:02:59 阅读次数:2205次
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
摹拟2进制加法,先逆置字符串,补全短串的前导0,最后注意首位进位!
class Solution {
public:
string addBinary(string a, string b) {
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
if(a.size()>b.size()) swap(a,b);
while(a.size()<b.size()) a+='0';
int add=0;
for(int i=0;i<a.size();i++)
{
int sum=add+a[i]+b[i]-'0'-'0';
b[i]=sum%2+'0';
add=sum/2;
}
if(add) b+='1';
reverse(b.begin(),b.end());
return b;
}
};
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠