3.4—字符串—Add Binary
来源:互联网 发布:全球贸易预警数据库 编辑:程序博客网 时间:2024/05/16 01:31
描述
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return ”100”.
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return ”100”.
#include <iostream>#include<string>#include<vector>using namespace std;string AddBinary(string str1, string str2){int length1 = str1.size();int length2 = str2.size();int length = length1>length2 ? length1 + 1 : length2 + 1;string res;for (int i = 1; i <= length; i++)res.push_back('0');char flag = '0';int p1 = length1 - 1;int p2 = length2 - 1;int p = length - 1;while (p1 >= 0 && p2 >= 0)//==={int temp = str1[p1] - '0' + str2[p2] - '0' + flag - '0';if (temp >= 2){flag = '1';temp = temp % 2;}res[p] = temp + '0';p--;p1--;p2--;}while (p1 >= 0)//==={int temp = str1[p1] - '0' + flag - '0';if (temp >= 2){flag = '1';temp = temp % 2;}res[p] = temp + '0';p--;p1--;}while (p2 >= 0)//==={int temp = str2[p2] - '0' + flag - '0';if (temp >= 2){flag = '1';temp = temp % 2;}res[p] = temp + '0';p--;p2--;}res[0] = res[0] - '0' + flag;if (res[0] == '0'){string subres = res.substr(1, length - 1);return subres;}elsereturn res;}int main(){string str1 = "11";string str2 = "01";string res = AddBinary(str1, str2);cout << res << endl;}
阅读全文
0 0
- 3.4—字符串—Add Binary
- Add Binary —LeetCode
- [LeetCode]—Add Binary 两个字符串二进制相加
- LeetCode Add Binary 字符串
- 字符串---Add Binary
- leetcode---add-binary---字符串
- LeetCode——Add Binary
- LeetCode——Add Binary
- LeetCode67——Add Binary
- LeetCode67——Add Binary
- Algorithms—67.Add Binary
- [leetcode] 【字符串】 67. Add Binary
- 3.4 add binary
- Python学习——leetcode(Add Binary)
- Add Binary —— Leetcode(重做)
- leetcode 067 —— Add Binary
- LeetCode题解——Add Binary
- Leetcode 67 —— Add Binary
- linux常用命令
- 欢迎使用CSDN-markdown编辑器
- laravel5.4 使用多字段查询分组报错
- 3d模型任意切割的思路(续)
- 使 Oracle 索引失效的七大限制条件
- 3.4—字符串—Add Binary
- js知识总结思维导图
- 浅谈工程师的调试法宝(二)---半主机的巧妙应用
- 编码
- kotlin Android中 findViewById()不能推导类型的错误
- Intellij IDEA的常用设置
- Android Coding 利器 之 掌握小技巧
- 1107. Social Clusters (30)并查集
- composer安装laravel