Skip to content

Commit 79c2132

Browse files
Merge branch 'TheAlgorithms:master' into master
2 parents 28b4c52 + ecb8a33 commit 79c2132

File tree

1 file changed

+119
-0
lines changed

1 file changed

+119
-0
lines changed

greedy_algorithms/binary_addition.cpp

Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
/**
2+
* @file binary_addition.cpp
3+
* @brief Adds two binary numbers and outputs resulting string
4+
*
5+
* @details The algorithm for adding two binary strings works by processing them
6+
* from right to left, similar to manual addition. It starts by determining the
7+
* longer string's length to ensure both strings are fully traversed. For each
8+
* pair of corresponding bits and any carry from the previous addition, it
9+
* calculates the sum. If the sum exceeds 1, a carry is generated for the next
10+
* bit. The results for each bit are collected in a result string, which is
11+
* reversed at the end to present the final binary sum correctly. Additionally,
12+
* the function validates the input to ensure that only valid binary strings
13+
* (containing only '0' and '1') are processed. If invalid input is detected,
14+
* it returns an empty string.
15+
* @author [Muhammad Junaid Khalid](https://github.com/mjk22071998)
16+
*/
17+
18+
#include <algorithm> /// for reverse function
19+
#include <cassert> /// for tests
20+
#include <iostream> /// for input and outputs
21+
#include <string> /// for string class
22+
23+
/**
24+
* @namespace
25+
* @brief Greedy Algorithms
26+
*/
27+
namespace greedy_algorithms {
28+
/**
29+
* @brief A class to perform binary addition of two binary strings.
30+
*/
31+
class BinaryAddition {
32+
public:
33+
/**
34+
* @brief Adds two binary strings and returns the result as a binary string.
35+
* @param a The first binary string.
36+
* @param b The second binary string.
37+
* @return The sum of the two binary strings as a binary string, or an empty
38+
* string if either input string contains non-binary characters.
39+
*/
40+
std::string addBinary(const std::string& a, const std::string& b) {
41+
if (!isValidBinaryString(a) || !isValidBinaryString(b)) {
42+
return ""; // Return empty string if input contains non-binary
43+
// characters
44+
}
45+
46+
std::string result;
47+
int carry = 0;
48+
int maxLength = std::max(a.size(), b.size());
49+
50+
// Traverse both strings from the end to the beginning
51+
for (int i = 0; i < maxLength; ++i) {
52+
// Get the current bits from both strings, if available
53+
int bitA = (i < a.size()) ? (a[a.size() - 1 - i] - '0') : 0;
54+
int bitB = (i < b.size()) ? (b[b.size() - 1 - i] - '0') : 0;
55+
56+
// Calculate the sum of bits and carry
57+
int sum = bitA + bitB + carry;
58+
carry = sum / 2; // Determine the carry for the next bit
59+
result.push_back((sum % 2) +
60+
'0'); // Append the sum's current bit to result
61+
}
62+
if (carry) {
63+
result.push_back('1');
64+
}
65+
std::reverse(result.begin(), result.end());
66+
return result;
67+
}
68+
69+
private:
70+
/**
71+
* @brief Validates whether a string contains only binary characters (0 or 1).
72+
* @param str The string to validate.
73+
* @return true if the string is binary, false otherwise.
74+
*/
75+
bool isValidBinaryString(const std::string& str) const {
76+
return std::all_of(str.begin(), str.end(),
77+
[](char c) { return c == '0' || c == '1'; });
78+
}
79+
};
80+
} // namespace greedy_algorithms
81+
82+
/**
83+
* @brief run self test implementation.
84+
* @returns void
85+
*/
86+
static void tests() {
87+
greedy_algorithms::BinaryAddition binaryAddition;
88+
89+
// Valid binary string tests
90+
assert(binaryAddition.addBinary("1010", "1101") == "10111");
91+
assert(binaryAddition.addBinary("1111", "1111") == "11110");
92+
assert(binaryAddition.addBinary("101", "11") == "1000");
93+
assert(binaryAddition.addBinary("0", "0") == "0");
94+
assert(binaryAddition.addBinary("1111", "1111") == "11110");
95+
assert(binaryAddition.addBinary("0", "10101") == "10101");
96+
assert(binaryAddition.addBinary("10101", "0") == "10101");
97+
assert(binaryAddition.addBinary("101010101010101010101010101010",
98+
"110110110110110110110110110110") ==
99+
"1100001100001100001100001100000");
100+
assert(binaryAddition.addBinary("1", "11111111") == "100000000");
101+
assert(binaryAddition.addBinary("10101010", "01010101") == "11111111");
102+
103+
// Invalid binary string tests (should return empty string)
104+
assert(binaryAddition.addBinary("10102", "1101") == "");
105+
assert(binaryAddition.addBinary("ABC", "1101") == "");
106+
assert(binaryAddition.addBinary("1010", "1102") == "");
107+
assert(binaryAddition.addBinary("111", "1x1") == "");
108+
assert(binaryAddition.addBinary("1x1", "111") == "");
109+
assert(binaryAddition.addBinary("1234", "1101") == "");
110+
}
111+
112+
/**
113+
* @brief main function
114+
* @returns 0 on successful exit
115+
*/
116+
int main() {
117+
tests(); /// To execute tests
118+
return 0;
119+
}

0 commit comments

Comments
 (0)