leetCode67.AddBinary字符串
67. Add Binary
庆城网站制作公司哪家好,找创新互联建站!从网页设计、网站建设、微信开发、APP开发、响应式网站建设等网站项目制作,到程序开发,运营维护。创新互联建站从2013年创立到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选创新互联建站。
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
思路:
1.将两个字符串按数组相加得到新数组。
2.将新数组转换成结果。
代码如下:
class Solution { public: string addBinary(string a, string b) { int sizeA = a.size(); int sizeB = b.size(); int carry = 0; vectorresult; string resultStr; if (sizeA < sizeB) return addBinary(b, a); for (int i = 0; i < sizeB; i++) { int cur = (a[sizeA - i - 1] - '0') + (b[sizeB - i - 1] - '0') + carry; if (cur < 2) { result.push_back(cur); carry = 0; } else if (cur == 2) { result.push_back(0); carry = 1; } else if (cur == 3) { result.push_back(1); carry = 1; } } for (int j = sizeB; j < sizeA; j++) { int cur = (a[sizeA - j - 1] - '0') + carry; if (cur < 2) { result.push_back((a[sizeA - j - 1] - '0') + carry); carry = 0; } else if (cur == 2) { result.push_back(0); carry = 1; } else if (cur == 3) { result.push_back(1); carry = 1; } } if (carry == 2) { result.push_back(0); result.push_back(1); } else if ( carry == 1) { result.push_back(1); } for (int k = 0; k < result.size(); k++) { if (result[result.size() - 1 - k] == 1) { resultStr.append(1, '1'); } else { resultStr.append(1, '0'); } } return resultStr; } };
2016-08-10 23:39:26
网站标题:leetCode67.AddBinary字符串
转载来源:http://hbruida.cn/article/jpedjc.html