binary add using strings

#include <iostream>
#include <algorithm>

std::string addBinary(std::string a, std::string b) {
    std::string result;
    int carry = 0;

    // Make sure strings are of equal length by prepending zeros
    int length = std::max(a.length(), b.length());
    a = std::string(length - a.length(), '0') + a;
    b = std::string(length - b.length(), '0') + b;

    // Perform binary addition
    for (int i = length - 1; i >= 0; --i) {
        int sum = (a[i] - '0') + (b[i] - '0') + carry;
        result.push_back(sum % 2 + '0');
        carry = sum / 2;
    }

    // If there's a carry left, add it to the result
    if (carry)
        result.push_back('1');

    // Reverse the result string
    std::reverse(result.begin(), result.end());

    return result;
}

int main() {
    std::string binary1 = "1101";
    std::string binary2 = "1011";

    std::string sum = addBinary(binary1, binary2);

    std::cout << "Binary Sum: " << sum << std::endl;

    return 0;
}