Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: Add Binary addition algorithm in C++ #3030

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

Open
Sujalgupta2p wants to merge 1 commit into TheAlgorithms:master
base: master
Choose a base branch
Loading
from Sujalgupta2p:patch-4
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
28 changes: 28 additions & 0 deletions bit_manipulation/add_binary.cpp
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#include <iostream>
#include <string>
#include <algorithm>

std::string add_binary(std::string a, std::string b) {
int i = a.size() - 1;
int j = b.size() - 1;
int carry = 0;
std::string result = "";

while (i >= 0 || j >= 0 || carry) {
int sum = carry;
if (i >= 0) sum += a[i--] - '0'; // convert char to int
if (j >= 0) sum += b[j--] - '0';
result += (sum % 2) + '0'; // convert int back to char
carry = sum / 2;
}

std::reverse(result.begin(), result.end());
return result;
}

int main() {
std::string a = "1010";
std::string b = "1011";
std::cout << "Sum: " << add_binary(a, b) << std::endl; // Output: 10101
return 0;
}

AltStyle によって変換されたページ (->オリジナル) /