Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
分析:该题需要注意的地方:1)两个string的长度可能不同 2)近位
借鉴leetcode-cpp.pdf的做法,先将两个string reverse,这样可以很方便的处理低位对齐的问题。代码如下:
1 class Solution { 2 public: 3 string addBinary(string a, string b) { 4 string res; 5 size_t n = a.size()>b.size()?a.size():b.size(); 6 reverse(a.begin(),a.end()); 7 reverse(b.begin(),b.end()); 8 int carry = 0; 9 for(int i = 0; i < n; i++){ 10 int ai = i<a.size()?a[i]-'0':0; 11 int bi = i<b.size()?b[i]-'0':0; 12 int val = (ai+bi+carry)%2; 13 carry = (ai+bi+carry)/2; 14 res.insert(res.begin(),val+'0'); 15 } 16 if(carry == 1) 17 res.insert(res.begin(),'1'); 18 return res; 19 } 20 };