思路:
首先求出最短长度,让他们对应加,将结果push_back到一个vector数组中。
- 如果他们长度相等,判断最后的进位是不是为1,如果为1则push_back进去,否则不push_back。
- 如果长度不想等,将较长的那个字符串剩下的部分和进位相加,同样将结果push_back进去。最后同样也要判断进位是否为1需要push_back进去。
其实就是模拟真实的手写计算过程。就是进位的设置需要注意一下。
code:
solotion.h
#include<string>
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
string addBinary(string a, string b) {
int alen=a.length(), blen=b.length();
int minlen = min(alen,blen);
int step=0;
vector<int> ans;
cout<<"minlen = "<<minlen<<endl;
for (int i=0; i<minlen; i++){
int ad1=a[alen-1-i]-'0', ad2=b[blen-1-i]-'0';
int tmpsum = ad1+ad2+step;
if (tmpsum>=2){
ans.push_back((tmpsum)%2);
step = (tmpsum)/2;
}else{
ans.push_back(tmpsum);
step = 0;
}
}
cout<<"ans.size = "<<ans.size()<<endl;
if (alen==minlen && blen!=minlen){
// b开始
cout<<"in b"<<endl;
int instep = step;
for (int i=minlen; i<blen; i++){
int ad1=b[blen-1-i]-'0', ad2=instep;
int tmpsum = ad1+ad2;
if (ad1+ad2>=2){
ans.push_back((tmpsum)%2);
instep = (tmpsum)/2;
}else{
ans.push_back(tmpsum);
instep = 0;
}
}
if (instep==1){
ans.push_back(instep);
}
}
else if (blen==minlen && alen!=minlen){
// a开始
cout<<"in a"<<endl;
int instep = step;
for (int i=minlen; i<alen; i++){
int ad1=a[alen-1-i]-'0', ad2=instep;
int tmpsum = ad1+ad2;
cout<<"tmpsum = "<<tmpsum<<endl;
if (ad1+ad2>=2){
ans.push_back((tmpsum)%2);
instep = (tmpsum)/2;
}else{
ans.push_back(tmpsum);
instep = 0;
}
}
if (instep==1)
ans.push_back(instep);
}
else{
// 长度相等
if (step==1){
ans.push_back(step);
}
}
for (int num:ans){
cout<<num<<" ";
}
cout<<endl;
string ansstr = "";
for (int i=ans.size()-1; i>=0; i--){
char tmpchar = ans[i]+'0';
ansstr +=tmpchar;
}
// cout<<ansstr;
return ansstr;
}
};
main.cpp
#include<iostream>
#include<string>
#include "solution.h"
using namespace std;
int main(){
Solution s;
string a = "1010", b = "11";
string ans = s.addBinary(a,b);
cout<<ans<<endl;
return 0;
}