LeetCode 67. Add Binary
来源:互联网 发布:常用电脑软件 编辑:程序博客网 时间:2024/05/16 07:28
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
// Only need to pay attention that adding is from the end of string.
This problem is similar to the add one problem. http://blog.csdn.net/github_34333284/article/details/51103310
#include <string>#include <iostream>using namespace std;// a = "11", b = "1" --> "100"string addBinary(string a, string b) { if(a.size() == 0) return b; if(b.size() == 0) return a; int aSize = a.size() - 1; int bSize = b.size() - 1; string res = ""; int overflow = 0; while(aSize >= 0 && bSize >= 0) { int tmp = a[aSize] - '0' + b[bSize] - '0' + overflow; overflow = tmp / 2; res = to_string(tmp % 2) + res; aSize--; bSize--; } while(aSize >= 0) { int tmp = a[aSize--] - '0' + overflow; overflow = tmp / 2; res = to_string(tmp % 2) + res; } while(bSize >= 0) { int tmp = b[bSize--] - '0' + overflow; overflow = tmp / 2; res = to_string(tmp % 2) + res; } if(overflow) res = "1" + res; return res;}int main(void) { string a = "11"; string b = "1"; string res = addBinary(a, b); cout << res << endl;}
Maybe It is better to make code clean.
#include <string>#include <iostream>using namespace std;string addBinary(string a, string b) { if(a.size() == 0) return b; if(b.size() == 0) return a; int aEnd = a.size() - 1; int bEnd = b.size() - 1; int overflow = 0; string res = ""; while(aEnd >= 0 || bEnd >= 0) { int sum = (aEnd < 0 ? 0 : (a[aEnd] - '0')) + (bEnd < 0 ? 0 : (b[bEnd] - '0')) + overflow; overflow = sum / 2; sum = sum % 2; res = to_string(sum) + res; aEnd--; bEnd--; } if(overflow) res = "1" + res; return res;}int main(void) { cout << addBinary("11", "1") << endl;}
0 0
- [LeetCode]67.Add Binary
- LeetCode --- 67. Add Binary
- [Leetcode] 67. Add Binary
- [leetcode] 67.Add Binary
- 【leetcode】67. Add Binary
- [leetcode] 67.Add Binary
- [leetcode] 67. Add Binary
- 【Leetcode】67. Add Binary
- 67. Add Binary LeetCode
- 【LeetCode】67. Add Binary
- leetcode--67. Add Binary
- leetcode 67. Add Binary
- LeetCode 67. Add Binary
- LeetCode *** 67. Add Binary
- leetcode 67. Add Binary
- 【leetcode】67.Add Binary
- LeetCode 67. Add Binary
- LeetCode-67.Add Binary
- Hash_node_pseudo类
- Hash_map()类
- Hash_map_pseudo类
- 算法学习的新阶段
- LeetCode 261. Graph Valid Tree(判断图是否为树)
- LeetCode 67. Add Binary
- SYBASE ASE 事务日志(transaction log)管理
- 最贵的一次保养
- 如何快速地安装Ubuntu SDK
- POJ3057 Evacuation 最大流+二分答案
- 取绝对值(in c语言)
- html入门(1)
- html入门(2)-标签学习
- LeetCode 49. Group Anagrams