leetcode: Add Binary
2014-07-04 20:21
309 查看
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) { if( a == "") return b; if( b == "") return a; string res; const int N = max( a.size(), b.size()); reverse( a.begin(), a.end()); reverse( b.begin(), b.end()); int carry = 0; for( int i = 0; i < N; ++i){ int ai = i < a.size() ? a[i] - '0' : 0; int bi = i < b.size() ? b[i] - '0' : 0; int val = ( ai + bi + carry) % 2; carry = ( ai + bi + carry) / 2; res.insert( res.begin(), val + '0'); } if( carry == 1) res.insert( res.begin(), '1'); return res; } };
相关文章推荐
- [Leetcode] Add Binary
- leetcode-67 add binary
- 【leetcode】String——Add Binary(67)
- LeetCode--Add Binary
- LeetCode---Add Binary
- LeetCode(67)题解: Add Binary
- [LeetCode]Add Binary
- 《leetCode》:Add Binary
- LeetCode笔记:67. Add Binary
- [LeetCode] Add Two Numbers、Divide Two Integers、Multiply Strings、Add Binary、Plus One
- [LeetCode] Add Binary
- Sum—LeetCode-67 Add Binary
- LeetCode小白菜笔记[16]:Add Binary
- leetcode_Add Binary
- Add Binary--LeetCode
- [Leetcode] Add Binary
- leetcode - Add Binary
- 【leetcode】第67题 Add Binary 题目+解析+JAVA代码
- [leetcode 67] Add Binary
- LeetCode Add Binary |My Solution