diff --git a/Add Binary b/Add Binary index a0d376c..495eadd 100644 --- a/Add Binary +++ b/Add Binary @@ -6,33 +6,29 @@ class Solution { public: string addBinary(string a, string b) { // Make both strings of equal length by prepending zeros - if(a.size() > b.size()) + if (a.size() > b.size()) { b = string(a.size() - b.size(), '0') + b; - else if(a.size() != b.size()) + } else if (a.size() < b.size()) { a = string(b.size() - a.size(), '0') + a; + } string result(a.size(), '0'); // Initialize result string with zeros bool carry = false; // Initialize carry to false - for(int i = a.size() - 1; i >= 0; --i) - { - if((a[i] == '1' && b[i] == '0') || (a[i] == '0' && b[i] == '1')) - { - result[i] = carry ? '0' : '1'; - } - else if(a[i] == '0' && b[i] == '0') - { - result[i] = carry ? '1' : '0'; - carry = false; - } - else if(a[i] == '1' && b[i] == '1') - { - result[i] = carry ? '1' : '0'; - carry = true; - } + // Iterate from the last character to the first + for (int i = a.size() - 1; i >= 0; --i) { + int sum = carry; // Start with the carry + sum += (a[i] - '0') + (b[i] - '0'); // Convert char to int and add + + // Determine the resulting bit and the new carry + result[i] = (sum % 2) + '0'; // Current bit + carry = sum / 2; // Update carry } - if(carry) + + // If there's a carry left, prepend it to the result + if (carry) { result = '1' + result; + } return result; }