leetcode Add Binary
题目连接
https://leetcode.com/problems/add-binary/
Add Binary
Description
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
class Solution { public: string addBinary(string a, string b) { reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); string ans = ""; size_t n = a.length(), m = b.length(); size_t i = 0, g = 0, c = min(n, m); for (; i < c; i++) { size_t k = a[i] - '0' + b[i] - '0' + g; ans += (k & 1) + '0'; g = k >> 1; } string &t = a.length() > b.length() ? a : b; c = t.length(); for (; i < c; i++) { size_t k = t[i] - '0' + g; ans += (k & 1) + '0'; g = k >> 1; } if (g) ans += '1'; reverse(ans.begin(), ans.end()); return ans; } };
By: GadyPu 博客地址:http://www.cnblogs.com/GadyPu/ 转载请说明