leetcode_字符串_67_二进制求和

/*
不明觉厉:
可以先以a = 1 b = 1来理解
*/
class Solution {
public:
string addBinary(string a, string b) {
string s;
//申请空间
s.reserve(a.size() + b.size());
int c = 0, i = a.size() - 1, j = b.size() - 1;
while(i >= 0 || j >= 0 || c == 1)
{
//补零
c += i >= 0 ? a[i–] - ‘0’ : 0;
c += j >= 0 ? b[j–] - ‘0’ : 0;
s.push_back((c & 1) + ‘0’);
c >>= 1;
}
reverse(s.begin(), s.end());
return s;
}
};
/补零的办法/
class Solution {
public:
string addBinary(string a, string b) {
int i=a.size()-1,j=b.size()-1,sum,index = 0;
string res="";
for(;i >= 0 || j >= 0; i–, j–) {
sum = index;
sum += i >= 0 ? a[i] - ‘0’ : 0;
sum += j >= 0 ? b[j] - ‘0’ : 0;
res +=to_string(sum % 2);
index = sum / 2;
}
res += index == 1 ? “1” : “”;
reverse(res.begin(),res.end());
return res;
}
};

你可能感兴趣的:(leetcode,数据结构与算法)