1. Brute Force
Algorithm
- Iterate through string
a, computing decimal value:valA = valA * 2 + (bit - '0'). - Iterate through string
b, computing decimal value:valB = valB * 2 + (bit - '0'). - Compute direct integer sum:
total = valA + valB. - Convert
totalback to binary string using continuous division by 2 or.toString(2). - Highlight overflow limitation: on binary inputs > 53 bits, floating-point IEEE-754 precision is lost.
Binary Radix Conversion & Direct Integer Addition Trace
2 of 2 questions left todayObservation: Scanning a = "1011" from MSB to LSB
Observation: Scanning a = "1011" from MSB to LSB. Process bit '1' at index 0.
Decision: Shift existing value by base 2: valA = 0 * 2 + 1 = 1.
Invariant: Numerical value of prefix "1" is 1_{10}.
#include <iostream>#include <string>#include <algorithm> // Note: Standard C++ does not have arbitrary-precision BigInt natively,// so manual binary addition is standard.class Solution {public: std::string addBinary(std::string a, std::string b) { std::string res = ""; int i = a.size() - 1, j = b.size() - 1, carry = 0; while (i >= 0 || j >= 0 || carry) { int sum = carry; if (i >= 0) sum += a[i--] - '0'; if (j >= 0) sum += b[j--] - '0'; res += std::to_string(sum % 2); carry = sum / 2; } std::reverse(res.begin(), res.end()); return res; }}; int main() { Solution sol; std::cout << sol.addBinary("11", "1") << std::endl; // Output: 100 std::cout << sol.addBinary("1010", "1011") << std::endl; // Output: 10101 return 0;}Time & Space Complexity
- Time complexity:
O(N + M)— Single pass over each binary string to compute its decimal value. - Space complexity:
O(1)— O(1) auxiliary space beyond scalar variables.
Why Brute Force Doesn't Scale:
Naive brute force re-examines already processed substrings multiple times.
For N = 105, O(N2) requires 1010 operations (TLE), while O(N) finishes in < 10ms.