LeetCode : Add Binary
2012-12-09 09:25
375 查看
Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
For example,
a =
"11"
b =
"1"
Return
"100".
class Solution { public: string addBinary(string a, string b) { // Start typing your C/C++ solution below // DO NOT write int main() function int i = a.size(); int j = b.size(); if(i == 0) return b; if(j == 0) return a; int carry = 0; string res; --j; --i; while(i >= 0 && j >= 0){ int temp = a[i] - '0' + b[j] - '0' + carry; carry = temp / 2; temp %= 2; res += (char)(temp + '0'); --i; --j; } while(i >= 0){ int temp = a[i] - '0' + carry; carry = temp / 2; temp %= 2; res += (char)(temp + '0'); --i; } while(j >= 0){ int temp = b[j] - '0' + carry; carry = temp / 2; temp %= 2; res += (char)(temp + '0'); --j; } if(carry){ res += "1"; } reverse(res.begin(), res.end()); return res; } };
相关文章推荐
- LEETCODE-Add Binary
- [Leetcode] Add Binary (Java)
- [LeetCode]Add Binary
- leetcode_67 add binary
- leetcode 67. Add Binary
- [leetcode] 67. Add Binary 解题报告
- leetcode 67. Add Binary (高精度加法)
- Leetcode - Add Binary
- Leetcode_67_Add Binary
- leetcode-67-Add Binary
- [LeetCode]67 Add Binary
- LeetCode67 Add Binary
- [Leetcode]Add Binary
- LeetCode:Add Binary
- LeetCode Add Binary
- LeetCode Add Binary
- LeetCode_Add Binary
- 和大神们学习每天一题(leetcode)-Add Binary
- [LeetCode] Add Binary
- LeetCode 67 Add Binary(二进制相加)(*)