Add Binary leetcode
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Subscribe to see which companies asked this question
二进制string加法,可优化代码,不过算法已经接近最优
string addBinary(string a, string b) { string ret; int lenA = a.size() - 1; int lenB = b.size() - 1; int cur; int add = 0; while (lenA >= 0 || lenB >= 0) { int numA = lenA >= 0 ? a[lenA] - '0' : 0; int numB = lenB >= 0 ? b[lenB] - '0' : 0; int num = numA + numB + add; cur = num & 1; add = num >> 1; ret.insert(0, 1, char('0' + cur)); lenA--; lenB--; } if (add == 1) ret.insert(0, 1, '1'); return ret; }