Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Add Binary #192

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 15 additions & 19 deletions Add Binary
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down