本文主要是介绍leetcode67:二进制求和,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接:67. 二进制求和 - 力扣(LeetCode)
class Solution {
public:string addBinary(string a, string b) {int stralen = a.size(), strblen = b.size();int curtc;int Maxlen = max(stralen, strblen);vector<int> stra;vector<int> strb;vector<int> strc;string ss1;for(int i = 0; i < a.size(); i++){int curta = a[i] - '0';stra.push_back(curta);}for(int i = 0; i < b.size(); i++){int curtb = b[i] - '0';strb.push_back(curtb);}if(stralen < strblen){int difference = strblen - stralen;for(int i = 0; i < difference; i++){stra.insert(stra.begin(), 0);}}if(stralen > strblen){int difference = stralen - strblen;for(int i = 0; i < difference; i++){strb.insert(strb.begin(), 0);}}for(int i = Maxlen - 1; i >= 1; i--){int curt = stra[i] + strb[i];if(curt > 1){curtc = stra[i] + strb[i] - 2;stra[i - 1]++;strc.push_back(curtc);}if(curt == 1){strc.push_back(1);}if(curt == 0){strc.push_back(0);}}if(stra[0] + strb[0] > 1){curtc = stra[0] + strb[0] - 2;strc.push_back(curtc);strc.push_back(1);}if(stra[0] + strb[0] == 1){strc.push_back(1);}if(stra[0] + strb[0] == 0){strc.push_back(0);}for(int i = 0; i < strc.size(); i++){ss1 += strc[i] + '0';}reverse(ss1.begin(), ss1.end());return ss1;}
};
这个题目算作中档题。这个题目实际上我把字符串转成每一个相应的数字了,然后从后往前遍历两个数组的每一位和,大于1在判断是2还是3,这个代码适用于二进制求和,要是其他进制求和,还得另外编写代码。
这篇关于leetcode67:二进制求和的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!