67.LeetCode Add Binary(easy)[字符串 大数相加处理]
来源:互联网 发布:免费idc销售系统源码 编辑:程序博客网 时间:2024/05/30 02:24
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
这个题是要实现对字符串完成二进制加法的功能,类似于大数加法这样的功能,需要考虑的是进位位、两个串不是一样长的时候需要补0的操作。这个题需要实现1+1 进位这样的规则设定。(要点:补0,进位处理)
具体思路如下:首先获取两个字符串的长度,对较短的字符串的前面添加‘0’字符,然后从数组的末尾开始相加,每次相加时注意修改进位标志,最后返回结果字符串。
class Solution {public: string addBinary(string a, string b) { int len1 = a.length(); int len2 = b.length(); if(len1>len2) { int t = len1-len2; while(t--) { b = "0"+b; } }else if(len1<len2) { int t = len2-len1; while(t--) { a = "0"+a; } } string c; char flag = '0'; //cout<<a<<" "<<b<<endl; for(int i=a.length()-1;i>=0;i--) { if(a[i]=='1'&&b[i]=='1') { c = flag + c; flag = '1'; }else if((a[i]=='1'&&b[i]=='0')||(a[i]=='0'&&b[i]=='1')) { if(flag == '0') { c = '1'+c; }else{ c = '0'+c; } }else { c = flag + c; flag = '0'; } } //cout<<flag<<endl; if(flag == '1') c = flag + c; return c; }};
0 0
- 67.LeetCode Add Binary(easy)[字符串 大数相加处理]
- LeetCode-67-Add Binary(数字/字符串处理)-Easy
- 【leetcode】Add Binary[easy]
- leetcode 67. Add Binary 二进制相加
- 大数相加,字符串处理
- Leetcode 67. Add Binary (Easy) (cpp)
- [LeetCode]—Add Binary 两个字符串二进制相加
- Add Binary 二进制相加 @LeetCode
- Leetcode:Add Binary 二进制相加
- [leetcode] 【字符串】 67. Add Binary
- [Leetcode 67, easy] Add Binary
- 【LeetCode】(67)Add Binary (Easy)
- <LeetCode><Easy> 67 Add Binary
- [leetcode] 415. Add Strings(大数相加)
- 大数相加、相乘 字符串处理
- LeetCode Add Binary 字符串
- leetcode---add-binary---字符串
- LeetCode 415. Add Strings (大数加法,字符串处理)
- ssh框架搭建的基本步骤
- 使用XStream将XML转化成对象,忽略没有关联的属性
- Cocos2dx:cocostudio 2.0 Text文本控件
- BASE64Encoder cannot be resolved to a type解决办法
- LeakCanary的使用
- 67.LeetCode Add Binary(easy)[字符串 大数相加处理]
- Perl 数据类型
- 7*8
- 机器学习总结二:逻辑回归Logistic Regression
- jstl c:forEach 一行排三个图片然后自动换行
- Android studio 报一下错时解决方案For example, the following line, in the gradle.properties file, sets the max
- 15电气李书鹏4月14日作业(1)
- Picasso的基本用法及如何加载网络图片和本地图片
- 不气馁,不牵强