本文主要是介绍C++ | Leetcode C++题解之第67题二进制求和,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
class Solution {
public:string addBinary(string a, string b) {string ans;reverse(a.begin(), a.end());reverse(b.begin(), b.end());int n = max(a.size(), b.size()), carry = 0;for (size_t i = 0; i < n; ++i) {carry += i < a.size() ? (a.at(i) == '1') : 0;carry += i < b.size() ? (b.at(i) == '1') : 0;ans.push_back((carry % 2) ? '1' : '0');carry /= 2;}if (carry) {ans.push_back('1');}reverse(ans.begin(), ans.end());return ans;}
};
这篇关于C++ | Leetcode C++题解之第67题二进制求和的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!