【LeetCode】(67)Add Binary (Easy)
来源:互联网 发布:网络问政平台的作用 编辑:程序博客网 时间:2024/06/08 17:09
题目
Add Binary
Total Accepted: 52390 Total Submissions: 212953My SubmissionsGiven two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
解析
我的思路是先把a和b扩充成一样长,用int的vector先保存下来他们和的值,例如retInt = [1,2]
再对和为2和3的数字专门讨论,最后转换为字符串即可。
如下
class Solution {public: string addBinary(string a, string b) { vector<int> retInt; int Len = a.length()>b.length()?a.length():b.length(); if (a.length()>=b.length()) { int i = a.length(); while (i != b.length()) { b.insert(b.begin(),'0'); } } else { int i = b.length(); while (i != a.length()) { a.insert(a.begin(),'0'); } } int aInt, bInt; for (int i = Len-1; i>=0 ;i--) { aInt = a[i]=='1'?1:0; bInt = b[i]=='1'?1:0; retInt.insert(retInt.begin(),aInt+bInt); } for (int i = Len-1; i>0 ;i--) { if (retInt[i]==2) { retInt[i] = 0; retInt[i-1]++; } else if (retInt[i]==3) { retInt[i] = 1; retInt[i-1]++; } } if (retInt[0]==2) { retInt[0] = 0; retInt.insert(retInt.begin(),1); } else if (retInt[0]==3) { retInt[0] = 1; retInt.insert(retInt.begin(),1); } string ret; for (int i = 0; i<retInt.size() ;i++) { if (retInt[i]==1) ret.push_back('1'); elseret.push_back('0'); } return ret; }};
大神的代码如下
//LeetCode, Add Binary// 时间复杂度O(n),空间复杂度O(1)class Solution {public:string addBinary(string a, string b) { string result; const size_t n = a.size() > b.size() ? a.size() : b.size(); reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); int carry = 0; for (size_t i = 0; i < n; i++) { const int ai = i < a.size() ? a[i] - '0' : 0; const int bi = i < b.size() ? b[i] - '0' : 0; const int val = (ai + bi + carry) % 2; carry = (ai + bi + carry) / 2; result.insert(result.begin(), val + '0'); } if (carry == 1) { result.insert(result.begin(), '1'); } return result; }};思路大概如下,先将两个字符串都翻转,这样就便于从后往前加,对于长度不够的,就当作0来计算。其他的步骤跟十进制的思路其实是一样的。
我们用十进制的思维来思考,如果16+95
我们算个位数,就是(6+5)/10=1,同时我们要计算进位数,也就是进的(6+5)%10 = 1
在我们计算十位数时,这个运算就需要考虑前面的影响,我们相当与是计算1+9+1,其他都雷同。
这个思路很好,也很规范,值得借鉴。
0 0
- [Leetcode 67, easy] Add Binary
- 【LeetCode】(67)Add Binary (Easy)
- <LeetCode><Easy> 67 Add Binary
- 【leetcode】Add Binary[easy]
- Leetcode OJ 67 Add Binary [Easy]
- LeetCode-67-Add Binary(数字/字符串处理)-Easy
- Easy 67题 Add Binary
- Leetcode 67. Add Binary (Easy) (cpp)
- LeetCode-Easy刷题(14) Add Binary
- [leetcode 67] Add Binary
- [LeetCode 67]Add Binary
- leetcode-67 Add Binary
- leetcode || 67、Add Binary
- LeetCode 67 Add Binary
- Add Binary - LeetCode 67
- LeetCode---(67) Add Binary
- leetcode[67]:Add Binary
- leetcode 67 Add Binary
- 实习的三个月
- OC中常用方法及概念
- codeforces 352C Jeff and Rounding 很有趣的一道题
- latex equation displaystyle or textstyle
- 循环链表的特性以及判断单链表是否有环(九)
- 【LeetCode】(67)Add Binary (Easy)
- 动态链接详解
- poj 3278 Catch That Cow
- App界面Tab选项卡之ViewPager
- uva 11168 - Airport(凸包)
- js的DOM(浏览器、网页尺寸)
- Fragment讲解
- [LeetCode] Unique Paths II
- 冒泡排序及两种优化方式