LeetCode | Add Binary
来源:互联网 发布:华为电视盒安装软件 编辑:程序博客网 时间:2024/05/17 02:21
题目:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
思路:
本质上是反序遍历两个字符串,然后依次相加,相加过程与http://blog.csdn.net/lanxu_yy/article/details/11688591类似。代码:
class Solution {public: string addBinary(string a, string b) { stack<bool> s; int cur_a = a.size() - 1; int cur_b = b.size() - 1; int carry = 0; while(cur_a > -1 || cur_b > -1){ int val_a = 0; if(cur_a > -1) { val_a = char2int(a[cur_a--]); } int val_b = 0; if(cur_b > -1) { val_b = char2int(b[cur_b--]); } int tmp = val_a + val_b + carry; carry = tmp / 2; s.push((tmp % 2) == 1); } if(carry == 1){ s.push(true); } string result; while(!s.empty()){ result.push_back(bool2char(s.top())); s.pop(); } return result; } int char2int(char c){ return c - '0'; } char bool2char(bool b){ if(b){ return '1'; } return '0'; }};
- 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
- Java 调用存储过程中的集合,如何传参
- Hive优化----基础知识以及效率的优化
- [Unity 3D] Unity 3D 性能优化(二)
- c#百度排名点击器编写,设置代理ip
- 不知道是第几次了
- LeetCode | Add Binary
- C# 中的MD5加密
- linux windows 共享 | linux vsftpd 配置
- DataGridView的Validating事件注册后删除操作的处理
- hdu 4737 A Bit Fun 数列(2013 ACM/ICPC Asia Regional Chengdu Online 1010)
- linux终端中输出彩色字体(C/SHELL)
- 2013 成都网络赛 1004 Minimum palindrome
- CSDN是不是废了!!!明明登陆了一直说没登陆!!!!
- 高德地图fragment 动态加载地图 嵌套问题