67. Add Binary
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) { if (a.size() < b.size()) swap(a, b); int n = a.size(); int al = a.length(); int bl = b.length(); bool mark = 0; vector<int> x(al); vector<int> y(al); string s = ""; for (int i = 0; i < al; ++i) x[i] = (a[i] - '0'); for (int i = 0; i < bl; ++i) y[i + al - bl] = (b[i] - '0'); for (int i = n - 1; i >= 0; --i) { int z = x[i] + y[i]; x[i] = z % 2; s = char(x[i] + '0') + s; if(i > 0) x[i - 1] += z / 2; else if (z / 2) { s = "1" + s; } } return s; } };
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: