题目:Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
思路:二进制加法和普通加法的思路没什么差别,甚至更简单。所需要注意的细节就是进位。从最低位开始,进位可能伴随计算直到最高位。所以每一位的加法运算都要将上一次的进位加进去。
对于某一位a和b,上一为的进位c,该为求和之后的和是(a+b+c)%2,进位是(a+b+c)/2
class Solution { public: string addBinary(string a, string b) { if(a.size()==0||a=="0") return b; if(b.size()==0||b=="0") return a; int lena=a.size()-1,lenb=b.size()-1,increase=0; string sum=""; while(lena>=0 && lenb>=0) { sum=std::to_string((a[lena]-'0' + b[lenb] - '0' + increase)%2) + sum; increase=(a[lena]-'0' + b[lenb] - '0' + increase)/2; lena--; lenb--; } while(lena>=0) { sum=std::to_string((increase+a[lena]-'0')%2)+sum; increase=(a[lena]-'0'+increase)/2; lena--; } while(lenb>=0) { sum=std::to_string((increase+b[lenb]-'0')%2)+sum; increase=(b[lenb]-'0'+increase)/2; lenb--; } if(increase==1) sum="1"+sum; return sum; } };