Leetcode 67. Add Binary
来源:互联网 发布:韩国snow软件 编辑:程序博客网 时间:2024/05/01 04:36
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”.
s思路:
1. 这类题,用string去模拟int做各种运算,比如这题的加法,还有之前的415. Add Strings, 44. Multiply Strings。
2. 和用int做运算比,我们之前就发现string容易reverse,可以利用这个特性,从低位加,进位到高位,这样不会每次加的时候都把结果插入到结果最前面导致后面值往后移动。
//方法1:先reverse两个数,然后从前往后做加法,结果再reverse。class Solution {public: string addBinary(string a, string b) { // reverse(a.begin(),a.end()); reverse(b.begin(),b.end()); string res=""; int m=a.size(),n=b.size(); int i=0,j=0,c=0; while(i<m||j<n||c==1){//这个条件设置很好,一个while就考虑完所有可能情况。 c=c+((i<m)?a[i++]-'0':0); //bug:写成c=c+(i<m)?a[i++]-'0':0;就错了 //因为+优先级可能高于问号,所以会先做加法,因此最好打括号。或者写成:c+=(i<m)?a[i++]-'0':0; c=c+((j<n)?b[j++]-'0':0); res+=(c%2+'0');//表示把结果转成char再添加到string末尾 c=c/2; } reverse(res.begin(),res.end()); return res; }};//方法2:不reverse, 每次把新的结果插入到string的最前面,时间复杂度高!class Solution {public: string addBinary(string a, string b) { // string res=""; int m=a.size()-1,n=b.size()-1,c=0; while(m>=0||n>=0||c==1){ c+=(m>=0)?a[m--]-'0':0; c+=(n>=0)?b[n--]-'0':0; res=char(c%2+'0')+res;//表示把结果转成char再添加到string末尾 //bug:这样写不对,res=c%2+'0'+res;需要char()转换!!相当to_string(c%2); c=c/2; } return res; }};
0 0
- [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
- 【leetcode】67.Add Binary
- LeetCode 67. Add Binary
- LeetCode-67.Add Binary
- 【转】Alsa音频编程【精华】
- 编程学习笔记之Java相关:接口(interface)的概念与使用
- 使用数字签名实现数据库记录防篡改(Java实现)
- 非对称加密算法
- redis安装
- Leetcode 67. Add Binary
- 1079. Total Sales of Supply Chain (25)
- android异常合集
- leecode 解题总结:16 3Sum Closest
- Keil Pack Installer 连接超时的解决办法
- P1020 导弹拦截
- P2668 斗地主
- Python 學習筆記系列一
- poj入门水题整理12