【LeetCode】(67)Add Binary (Easy)
2015-08-21 22:54
483 查看
题目
Add Binary
Total Accepted: 52390 TotalSubmissions: 212953My Submissions
Question
Solution
Given 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'); else ret.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,其他都雷同。
这个思路很好,也很规范,值得借鉴。
相关文章推荐
- Python Elasticsearch api
- iOS开发之网络篇-各种网络状态码
- NBUT 1456 Orianna (DP)
- uva 1453 - Squares(旋转卡壳)
- 黑马程序员——OC的内存管理——ARC
- linux下50个常用命令
- Libevent源码分析-timer和signal处理
- ssh常见错误
- 创建mysql数据库并指定编码
- 傻瓜都能看懂的网络流ek算法(poj1273)
- 【C++】万年历(时间计数器)
- Android的Service组件
- 要有被打断仍能够继续学习的能力
- 删除数据库mysql
- uva 10256 - The Great Divide(凸包)
- Easy Ui Layout控件
- 作业,大美农登录界面和设置密码
- 冒泡排序及两种优化方式
- js编程(选项卡)
- 今天开博客啦