[LeetCode] Add Binary
来源:互联网 发布:心理评测软件 编辑:程序博客网 时间:2024/06/05 22:48
问题:
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
分析:
简单的一道题,功夫在于代码写得简洁漂亮。
代码:
class Solution {public:string addBinary(string a, string b) {int index = max(a.length(), b.length());string result (index + 1, '0');int carry = 0;int i = a.length() - 1;int j = b.length() - 1;while (i>= 0 || j >= 0 || carry > 0) {int a_num = (i >= 0? a[i --] - '0' : 0);int b_num = (j >= 0? b[j --] - '0' : 0);result[index --] = ((a_num + b_num + carry) % 2) + '0';carry = ((a_num + b_num + carry) > 1);}if (result[0] == '0')return result.substr(1);return result;}};
0 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
- Android TextView使用HTML处理字体样式、显示图片等
- How can one start solving Dynamic Programming problems?
- 用topcoder准备cs 面试
- const=0
- iOS Dev (13) UITableView
- [LeetCode] Add Binary
- 2014,年终述职
- 【古董界掌眼的GBR平台总代:1114811158】第一章
- 万古长夜,第一缕光GBR平台1114811158开号。
- linux 硬盘坏道检测维护
- 索引器练习 照片 相册 索引器
- bsoj2173——trie模版题
- Linux c编程一站式学习笔记(06), 位移操作
- Two Sum