A class to perform binary addition of two binary strings.
More...
|
std::string | addBinary (const std::string &a, const std::string &b) |
| Adds two binary strings and returns the result as a binary string.
|
|
|
bool | isValidBinaryString (const std::string &str) const |
| Validates whether a string contains only binary characters (0 or 1).
|
|
A class to perform binary addition of two binary strings.
Definition at line 31 of file binary_addition.cpp.
◆ addBinary()
std::string greedy_algorithms::BinaryAddition::addBinary |
( |
const std::string & | a, |
|
|
const std::string & | b ) |
|
inline |
Adds two binary strings and returns the result as a binary string.
- Parameters
-
a | The first binary string. |
b | The second binary string. |
- Returns
- The sum of the two binary strings as a binary string, or an empty string if either input string contains non-binary characters.
Definition at line 40 of file binary_addition.cpp.
40 {
42 return "";
43
44 }
45
47 int carry = 0;
48 int maxLength = std::max(a.size(), b.size());
49
50
51 for (int i = 0; i < maxLength; ++i) {
52
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
57 int sum = bitA + bitB + carry;
59 result.push_back((sum % 2) +
60 '0');
61 }
62 if (carry) {
64 }
67 }
bool isValidBinaryString(const std::string &str) const
Validates whether a string contains only binary characters (0 or 1).
uint64_t result(uint64_t n)
T sum(const std::vector< std::valarray< T > > &A)
◆ isValidBinaryString()
bool greedy_algorithms::BinaryAddition::isValidBinaryString |
( |
const std::string & | str | ) |
const |
|
inlineprivate |
Validates whether a string contains only binary characters (0 or 1).
- Parameters
-
str | The string to validate. |
- Returns
- true if the string is binary, false otherwise.
Definition at line 75 of file binary_addition.cpp.
75 {
76 return std::all_of(str.begin(), str.end(),
77 [](char c) { return c == '0' || c == '1'; });
78 }
The documentation for this class was generated from the following file: