[leetcode]Add Binary
2013-07-24 22:57
316 查看
class Solution { public: char add(char a, char b, char c, char &carry){ int result = a - '0' + b -'0' + c-'0'; if(result == 0){ carry = '0'; return '0'; }else if(result == 1){ carry = '0'; return '1'; }else if(result == 2){ carry = '1'; return '0'; }else{ carry = '1'; return '1'; } } string addBinary(string a, string b) { // Start typing your C/C++ solution below // DO NOT write int main() function if(a.empty() || b.empty()) return ""; if(b.size() > a.size()) swap(a,b); int p = a.size()-1; int q = b.size()-1; string c = a; char carry = '0'; char nc; while(q >= 0){ c[p] = add(a[p], b[q], carry, nc); carry = nc; p--; q--; } while(p >= 0){ c[p] = add(a[p], '0', carry, nc); carry = nc; p--; } if(carry == '1'){ c.insert(c.begin(), '1'); } return c; } };
相关文章推荐
- 【leetcode】第67题 Add Binary 题目+解析+JAVA代码
- LeetCode(67) Add Binary
- leetcode Add Binary
- LeetCode题解:Add Binary
- leetcode - Add Binary
- LeetCode:Plus One, Add Binary, Sqrt(x), Climbing Stairs
- LeetCode 67: Add Binary
- [Leetcode 28] 67 Add Binary
- LeetCode 067 Add Binary
- leetcode - Add Binary
- 【leetcode】Add Binary-----Java
- [leetcode] Add Binary
- [Leetcode]Add Binary
- LeetCode No.67 Add Binary
- LeetCode--Add Binary
- Leetcode 67 Add Binary 大数加法+字符串处理
- 【leetcode刷题笔记】Add Binary
- LeetCode 面试:Add Binary
- 【LeetCode】Add Binary
- Leetcode: Add Binary