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”.

#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;}

原创粉丝点击