TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
|
Adds two binary numbers and outputs resulting string. More...
#include <algorithm>
#include <cassert>
#include <iostream>
#include <string>
Go to the source code of this file.
Classes | |
class | greedy_algorithms::BinaryAddition |
A class to perform binary addition of two binary strings. More... | |
Namespaces | |
namespace | greedy_algorithms |
for string class | |
Functions | |
static void | tests () |
run self test implementation. | |
int | main () |
main function | |
Adds two binary numbers and outputs resulting string.
The algorithm for adding two binary strings works by processing them from right to left, similar to manual addition. It starts by determining the longer string's length to ensure both strings are fully traversed. For each pair of corresponding bits and any carry from the previous addition, it calculates the sum. If the sum exceeds 1, a carry is generated for the next bit. The results for each bit are collected in a result string, which is reversed at the end to present the final binary sum correctly. Additionally, the function validates the input to ensure that only valid binary strings (containing only '0' and '1') are processed. If invalid input is detected, it returns an empty string.
Definition in file binary_addition.cpp.
int main | ( | void | ) |
main function
To execute tests
Definition at line 116 of file binary_addition.cpp.
|
static |
run self test implementation.
Definition at line 86 of file binary_addition.cpp.