Leetcode 数 Add Binary
来源:互联网 发布:linux 请求url命令 编辑:程序博客网 时间:2024/06/06 20:32
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Add Binary
Total Accepted: 9509 Total Submissions: 37699Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
题意:给定两个二进制字符串,返回它们的和
思路:
1.按最长的循环,短的前面补零
2.因为变量少,不用考虑节省空间,定义为int最行了
3.用二进制可能会快一点。不过实现会麻烦一些
复杂度:时间O(m+n),空间O(m+n)
class Solution {public: string addBinary(string a, string b){ string result; int carry = 0; int scale = 2; for(int i = a.size() - 1, j = b.size() - 1; i >= 0 || j >= 0; i--,j--){ int ai = i > -1 ? a[i] - '0' : 0; int bi = j > -1 ? b[j] - '0' : 0; int residual = (ai + bi + carry) % scale; carry = (ai + bi + carry) / scale; result.insert(result.begin(), residual + '0'); } if(carry) result.insert(result.begin(), carry + '0'); return result; }};
0 0
- Leetcode 数 Add Binary
- LeetCode-67 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 58: Add Binary
- leetcode Add Binary
- [LeetCode] Add Binary
- 【leetcode】Add Binary
- [LeetCode]Add Binary
- [leetcode]Add Binary
- LeetCode-Add Binary
- [leetcode] Add Binary
- Java回调函数使用
- 读取配置文件内容
- HDFS Federation
- 从一道面试题谈linux下fork的运行机制
- 鼠标类型
- Leetcode 数 Add Binary
- 基于linux的hadoop环境搭建
- Linux下使用多个不同版本的R
- 干货系列2:看看Java桌面应用开发的职业发展空间与必备技能
- 模糊距离分析
- Activity四种启动方式 standard singleTop singleTask singleInstance
- (ASP.NET MVC4 入门学习笔记)学习自己建项目1----建项目、配路由、配数据库
- Broadcom Nexus学习 (一) Graphics,Display
- Segment Tree - Sum of given range