leetcode-67-Add Binary
2015-08-03 18:41
423 查看
Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a =
b =
Return
两字符串表示的2进制数。求它们的和。
直接模拟,从最后一位开始每一位都相加,结果保存在栈中。
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 == '0' && b[m] == '0') { if (add == 1) s.push('1'); else s.push('0'); add = 0; } else if (a == '0' && b[m] == '1' ||a == '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 == '1') { if (add == 1) {s.push('0');add = 1;} else {s.push('1');add = 0;} } else if (a == '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; } };
相关文章推荐
- Java connect to MySQL through JDBC
- Simple calculations
- Android批量打包提速 - 1分钟900个市场不是梦
- Android批量打包提速 - 1分钟900个市场不是梦
- UML 类图
- 网页中的各种高度height
- SDNU 1331.Kick Veges' Ass【SDNU2015暑期集训队测验I】【二分法】【8月3】
- xcode老版本 照片问题
- 无私才能无畏,正气才能坦然
- 解析STM32启动流程
- 软件开发中常遇到的问题
- measure_pads_subpix.hdev找芯片管脚大小 相关例程学习
- 第二十七篇:SOUI中控件属性查询方法
- Java Mybatis Plugin插件实现分表路由规则
- 【leetcode】Subsets II
- CocoaPods安装及使用
- Loadrunner集合点
- linux下避免文件覆盖的命令
- swift函数
- hdu2421