TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
greedy_algorithms::BinaryAddition Class Reference

A class to perform binary addition of two binary strings. More...

Public Member Functions

std::string addBinary (const std::string &a, const std::string &b)
 Adds two binary strings and returns the result as a binary string.
 

Private Member Functions

bool isValidBinaryString (const std::string &str) const
 Validates whether a string contains only binary characters (0 or 1).
 

Detailed Description

A class to perform binary addition of two binary strings.

Definition at line 31 of file binary_addition.cpp.

Member Function Documentation

◆ 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
aThe first binary string.
bThe 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 ""; // 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 }
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
strThe 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: