Skip to content

Create 27 NOV 27 November Add Binary Strings #3

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

Merged
merged 1 commit into from
Nov 27, 2022
Merged
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
45 changes: 45 additions & 0 deletions 27 NOV 27 November Add Binary Strings
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
class Solution{
public:
string addBinary(string A, string B)
{
string res;

int i = A.length() - 1;

int j = B.length() - 1;

int carry = 0;

while(i >= 0 || j >= 0){

int sum = carry;

if(i >= 0) sum += A[i--] - '0';

if(j >= 0) sum += B[j--] - '0';

carry = sum > 1 ? 1 : 0;

res += to_string(sum % 2);

}

if(carry) res += to_string(carry);

reverse(res.begin(), res.end());

i = 0;

while(res[i] == '0')

{

res.erase(0, 1);

}



return res;
}
};