[LintCode] Add Binary 二进制数相加

Given two binary strings, return their sum (also a binary string).

Have you met this question in a real interview?
Yes
Example

a = 11

b = 1

Return 100

LeetCode上的原题,请参见我之前的博客Add Binary

class Solution {
public:
/**
* @param a a number
* @param b a number
* @return the result
*/
string addBinary(string& a, string& b) {
string res = "";
int m = a.size() - , n = b.size() - , carry = ;
while (m >= || n >= ) {
int p = m >= ? a[m--] - '' : ;
int q = n >= ? b[n--] - '' : ;
int sum = p + q + carry;
res = to_string(sum % ) + res;
carry = sum / ;
}
return carry == ? "" + res : res;
}
};
上一篇:nodejs+express+socket.io


下一篇:【ASP.NET Web API教程】2.3.7 创建首页