LeetCode Add Binary
1 class Solution { 2 public: 3 string addBinary(string a, string b) { 4 string res; 5 int carry = 0, s = 0; 6 int apos = a.length() - 1; 7 int bpos = b.length() - 1; 8 int astp = 0, bstp = 0; 9 // skip leading zero(s) 10 for (; astp < apos && a[astp] == '0'; astp++); 11 for (; bstp < bpos && b[bstp] == '0'; bstp++); 12 // a/b pos validation 13 bool apv = apos >= astp, bpv = bpos >= bstp; 14 // addition 15 while(apv || bpv) { 16 if (apv) s += a[apos] - '0'; 17 if (bpv) s += b[bpos] - '0'; 18 carry = s > 1; 19 s = s & 0x1; 20 res.push_back(s ? '1' : '0'); 21 apos--, bpos--, s = carry; 22 apv = apos >= astp, bpv = bpos >= bstp; 23 } 24 if (carry) res.push_back('1'); 25 if (res.empty()) { 26 res.push_back('0'); 27 } else { 28 reverse(res.begin(), res.end()); 29 } 30 return res; 31 } 32 };
没研究过C++里字符串操作的效率问题,直接使用+进行字符串连接并重新赋值回去不知道额外开销大不大,从提交的结果来看和用push_back的没什么区别,有的甚至更快