[leetcode] 【字符串】 67. Add Binary
来源:互联网 发布:淘宝图片拍摄技巧 编辑:程序博客网 时间:2024/05/16 10:02
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
题意
两个字符串表示两个二进制数,返回二进制的字符串表示他们的和。
题解
我是先翻转再操作,这样可以从下标0开始操作。
注意长度,以及最后进位。
class Solution {public: string addBinary(string a, string b) { const int n=a.size()>b.size() ? a.size() :b.size(); reverse(a.begin(),a.end());//翻转字符串,方便从低位开始操作 reverse(b.begin(),b.end()); string res; int carry=0; for(int i=0;i<n;i++) { const int ai=i<a.size() ? a[i]-'0':0; const int bi=i<b.size() ? b[i]-'0':0; const int val=(ai+bi+carry)%2; res.insert(res.begin(),val+'0'); carry=(ai+bi+carry)/2; } if(carry==1) res='1'+res; return res; }};
0 0
- [leetcode] 【字符串】 67. Add Binary
- LeetCode Add Binary 字符串
- leetcode---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】67. Add Binary
- 67. Add Binary LeetCode
- 【LeetCode】67. Add Binary
- leetcode--67. Add Binary
- leetcode 67. Add Binary
- LeetCode 67. Add Binary
- LeetCode *** 67. Add Binary
- leetcode 67. Add Binary
- Java或Web中解决所有路径问题
- leetcode 299. Bulls and Cows
- ADB Commands Cheat Sheet
- Spring MVC 获取请求参数的几种方法
- cocos2dx之onEnter,onExit
- [leetcode] 【字符串】 67. Add Binary
- 面向对象多继承
- 模板类错误程序
- LeetCode-349&350.Intersection of Two Arrays
- Mybatis学习与Spring MVC 的集成(6)
- 高并发的简单处理方法
- tornado study 1
- HttpURLConnection请求数据
- 从线行回归到高斯过程分类