LeetCode 67 Add Binary
来源:互联网 发布:北京linux培训机构 编辑:程序博客网 时间:2024/06/06 18:20
题意:
两个二进制数相加,输出结果
思路:
各种模拟均可,比如先把A和B倒过来,再按位相加,最后把结果再倒回来。
不过为了快,我是这样做的——假设A比B长,那么我对位相加B的长度。这时如果没有进位,那么A长出B的部分就不会变了;如果有进位,那么继续往A的高位加,直到某一次进位为0,那么更高位的A就不变了;如果直到最后还有进位,那就最前面添加一个最高位1。
代码:
class Solution {public: string addBinary(string a, string b) { if (a.size() < b.size()) { swap(a, b); } int i = a.size() - 1; int j = b.size() - 1; stringstream ss; int add = 0; while (j >= 0) { add += a[i] + b[j] - '0' - '0'; --i; --j; ss << (add & 1); add >>= 1; } while (add && i >= 0) { add += a[i] - '0'; --i; ss << (add & 1); add >>= 1; } if (add > 0) { ss << add; string ans = ss.str(); reverse(ans.begin(), ans.end()); return ans; } string ans = ss.str(); reverse(ans.begin(), ans.end()); return a.substr(0, i + 1) + ans; }};
阅读全文
0 0
- [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
- Leetcode# 67 Add Binary
- leetcode 67: Add Binary
- leetcode-67-Add Binary
- Leetcode#67||Add Binary
- [Leetcode]#67 Add Binary
- leetcode 67Add Binary
- Leetcode 67:Add Binary
- leetcode 67 Add Binary
- [leetcode 67] Add Binary
- 强化学习中的backups
- 决策树
- 算法机考模拟题
- python queue模块
- Spark运行原理
- LeetCode 67 Add Binary
- 主成分分析的计算方法
- 50个必备的实用jQuery代码段+ 可以直接拿来用的15个jQuery代码片段
- ASP.NET WebApi 路由配置
- 正则匹配
- C++标准转换运算符const_cast
- 分享一个内容管理系统网站
- hasChildNodes方法;ownerDocument;
- Event Service