[Leetcode] Add Binary
来源:互联网 发布:苹果cms地址怎么改 编辑:程序博客网 时间:2024/05/11 02:42
Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
思路: 对齐, 计算当前位和进位;
如果位较长,让我想到了先行进位加法器,不过这里的计算不能并行,也无什么效果。
//add Binaryclass Solution {public: string addBinary(string a, string b) { // Start typing your C/C++ solution below // DO NOT write int main() functionstring c;int flag=0;int lena = a.size();int lenb = b.size();int len = abs(lena-lenb);string append(len,'0');if(lena>lenb){b = append + b;c.resize(lena,'0');}else{a = append + a;c.resize(lenb,'0');}for(int j=c.size()-1;j>=0;j--){int current = (a[j]-'0') ^(b[j]-'0') ^flag;if((a[j]-'0') +(b[j]-'0') +flag >1)flag = 1;else flag = 0;c[j] = current+'0';}if(flag == 1)c = '1'+ c;return c; }};
- LeetCode: Add Binary
- [Leetcode] Add Binary
- LeetCode Add Binary
- Leetcode: Add Binary
- [Leetcode] Add Binary
- LeetCode : Add Binary
- LeetCode Add Binary
- [LeetCode] Add Binary
- leetcode 58: Add Binary
- leetcode Add Binary
- [LeetCode] Add Binary
- 【leetcode】Add Binary
- [LeetCode]Add Binary
- [leetcode]Add Binary
- LeetCode-Add Binary
- [leetcode] Add Binary
- LeetCode - Add Binary
- leetcode:Add Binary
- 八、关系代数
- (个人原创) 安装git server 解决问题大全
- ORACLE修改表空间方法
- 修改查看源文件工具
- Oracle常见数据类型
- [Leetcode] Add Binary
- 使用Core Data
- mycollection
- mongoDB中基本操作
- Ext json序列化
- 抗日系列之中途岛战役
- 编程学习
- 关于Java的RandomAccessFile的中文处理
- Android 程式开发:(十四)显示图像 —— 14.2 ImageSwitcher