Add Binary 二進位制相加
阿新 • • 發佈:2018-12-24
class Solution {
public:
string addBinary(string a, string b) {
size_t n=a.size()>b.size()?a.size():b.size();
int carry=0;
string result;
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
for(int i=0;i<n;i++)
{
int aval=i<a.size()?a[i]-'0':0;
int bval=i<b.size()?b[i]-'0':0;
int temp=aval+bval+carry;
carry=temp/2;
temp%=2;
result.insert(result.begin(),temp+'0');
}
if(carry>0)
result.insert(result.begin(),carry+'0');
return result;
}
};
public:
string addBinary(string a, string b) {
size_t n=a.size()>b.size()?a.size():b.size();
int carry=0;
string result;
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
for(int i=0;i<n;i++)
{
int aval=i<a.size()?a[i]-'0':0;
int bval=i<b.size()?b[i]-'0':0;
int temp=aval+bval+carry;
carry=temp/2;
temp%=2;
result.insert(result.begin(),temp+'0');
}
if(carry>0)
result.insert(result.begin(),carry+'0');
return result;
}
};