leetcode-67-Add Binary
来源:互联网 发布:php上传图片压缩大小 编辑:程序博客网 时间:2024/05/17 06:59
Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
两字符串表示的2进制数。求它们的和。
直接模拟,从最后一位开始每一位都相加,结果保存在栈中。
class Solution {public: string addBinary(string a, string b) { stack<int>s; int n = a.size() - 1,m = b.size() - 1; int add = 0; //进位 while (n >= 0 && m >= 0) { // 计算每一位的结果,存在栈中 if (a[n] == '0' && b[m] == '0') { if (add == 1) s.push('1'); else s.push('0'); add = 0; } else if (a[n] == '0' && b[m] == '1' ||a[n] == '1' && b[m] == '0') { if (add == 1) {s.push('0');add = 1;} else {s.push('1');add = 0;} } else { if (add == 1) s.push('1'); else s.push('0'); add = 1; } n--; m--; } // 两字符串有一字符串为空 则另作讨论 if (n < 0 && m < 0) { if (add == 1) s.push('1'); } else if (n >= 0 && m < 0) { while (n >= 0) { if (a[n] == '1') { if (add == 1) {s.push('0');add = 1;} else {s.push('1');add = 0;} } else if (a[n] == '0') { if (add == 1 ) s.push('1'); else s.push('0'); add = 0; } n--; } if (add == 1) s.push('1'); } else if (n < 0 && m >= 0) { while (m >= 0) { if (b[m] == '1') { if (add == 1) {s.push('0');add = 1;} else {s.push('1');add = 0;} } else if (b[m] == '0') { if (add == 1 ) s.push('1'); else s.push('0'); add = 0; } m--; } if (add == 1) s.push('1'); } string c; while(!s.empty()) { // 每一位的结果,从栈中取出,存入string中 c += s.top(); s.pop(); } return c; }};
1 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
- OGNL总结
- min-height和max-height
- [经验] 基于Xmodem的STM32的IAP升级【转】
- AD7175-2使用问题记录
- OC学习:NSURL讲解和OC中图片下载
- leetcode-67-Add Binary
- JS中this
- SDNU 1331.Kick Veges' Ass【SDNU2015暑期集训队测验I】【二分法】【8月3】
- hdu2421
- Watches OpenCart 主题模板 ABC-0088
- Unity3d
- win8下安装ubuntu12.04的悲催历程
- HDU 4352 XHXJ's LIS 数位状压DP
- 206 Reverse Linked List