文章目录
- 1. 题目链接
- 2. 题目代码
- 3.感受
1. 题目链接
二进制求和
2. 题目代码
class Solution {
public:
string addBinary(string a, string b) {
vector<int> stringA;
vector<int> stringB;
int lengthOfA = a.length();
int lengthOfB = b.length();
for(int subscriptOfA = 0; subscriptOfA < lengthOfA; subscriptOfA ++){
stringA.push_back(a[subscriptOfA] - '0');
}
for(int subscriptOfB = 0; subscriptOfB < lengthOfB; subscriptOfB ++){
stringB.push_back(b[subscriptOfB] - '0');
}
if(lengthOfA > lengthOfB){
stringB.insert(stringB.begin(), lengthOfA - lengthOfB , 0);
}
if(lengthOfB > lengthOfA){
stringA.insert(stringA.begin(), lengthOfB - lengthOfA , 0);
}
reverse(stringA.begin(), stringA.end());
reverse(stringB.begin(), stringB.end());
vector<int> result;
int carry = 0;
for(int subscript = 0; subscript < stringA.size(); subscript ++){
result.push_back((stringA[subscript] + stringB[subscript] + carry) % 2);
if(stringA[subscript] + stringB[subscript] + carry >= 2){
carry = 1;
}else{
carry = 0;
}
}
if(carry == 1){
result.push_back(1);
}
string finallResult;
for(int subscript = result.size() - 1; subscript >= 0; subscript --){
finallResult += result[subscript] + '0';
}
return finallResult;
}
};
3.感受
之前解题的过程中,老是想着想着就把自己绕进去了,一直解不出来。之后就是有空就去试试。今天终于解出来了。
上图还只显示了提交以后的结果,还有很多次直接编译失败,就没提交