二进制求和
2017-03-16 19:31
204 查看
给定两个二进制字符串,返回他们的和(用二进制表示)。
样例
a =
b =
返回
解题思路:巧用a[i] - '0'
样例
a =
11
b =
1
返回
100
解题思路:巧用a[i] - '0'
class Solution { public: /** * @param a a number * @param b a number * @return the result */ string addBinary(string& a, string& b) { // Write your code here string result; int temp = 0; auto length = a.size() > b.size() ? a.size() : b.size(); reverse(a.begin(),a.end()); reverse(b.begin(),b.end()); for (auto i = 0; i < length; i++) { int aa = i < a.size() ? a[i] - '0' : 0; int bb = i < b.size() ? b[i] - '0' : 0; int val = (aa + bb + temp) % 2; temp = (aa + bb + temp) / 2; result.insert(result.begin(), val + '0'); } if (temp == 1) { result.insert(result.begin(), 1 + '0'); } return result; } };
相关文章推荐
- LintCode(容易)二进制求和遇到的bug
- 二进制求和,lintcode
- 二进制求和(LintCode)
- LintCode Add Binary 二进制求和
- 二进制求和
- LintCode | 408. 二进制求和
- lintcode ----二进制求和
- 算法学习笔记--4. 二进制求和
- LintCode408:二进制求和
- 二进制求和
- LintCode 二进制求和
- 容易 二进制求和
- 二进制字符串求和-leetcode Add Binary
- 链表求和 & 二进制求和
- LintCode之408 二进制求和
- 二进制求和
- 67. Add Binary (二进制求和)
- Java-不使用运算符,使用二进制符号进行求和
- 2013暑假江西联合训练赛(赛后) 二进制求和 (树状数组,这里需要变形下)
- 二进制求和