-
-
Notifications
You must be signed in to change notification settings - Fork 7.6k
feat: Added Binary Addition Algorithm #2802
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
Merged
+119
−0
Merged
Changes from 39 commits
Commits
Show all changes
49 commits
Select commit
Hold shift + click to select a range
47af70e
Digit Separation Algorithm added
mjk22071998 48f42a7
Merge branch 'TheAlgorithms:master' into master
mjk22071998 011c4e2
feat: Added namespace greedy_algoriithms
mjk22071998 76edb15
"Updated digit separation code: added comments and docstrings, change…
mjk22071998 57f61a6
feat: Made test function and removed extra whitespaces
mjk22071998 9c0034c
removed some more whitespaces
mjk22071998 cba0eb9
Update greedy_algorithms/digit_separation.cpp
mjk22071998 d3edb52
fix: terminate multiline comment
realstealthninja 1fb86db
Update greedy_algorithms/digit_separation.cpp
mjk22071998 ad03474
Update greedy_algorithms/digit_separation.cpp
mjk22071998 5f392b9
Update greedy_algorithms/digit_separation.cpp
mjk22071998 373e1df
Update greedy_algorithms/digit_separation.cpp
mjk22071998 af077d2
Corrected test function
mjk22071998 18b6546
Update greedy_algorithms/digit_separation.cpp
mjk22071998 87b955b
Update greedy_algorithms/digit_separation.cpp
mjk22071998 a585834
remove redundant declaration
mjk22071998 ef954a8
Corrected tests
mjk22071998 1427474
file clang linted
mjk22071998 a0f488b
Merge branch 'master' into master
mjk22071998 051448f
Merge branch 'master' into master
mjk22071998 3f04892
"Moved method implementations from outside to inside class definition"
mjk22071998 ba56880
fowardOrder to forwardOrder on line 122
mjk22071998 40ac103
Removed Class scope resolution form digitSeparationReverseOrder function
mjk22071998 12d8d53
Removed Class scope resolution form digitSeparationForwardOrderfunction
mjk22071998 28f6901
docs: documentation updated
mjk22071998 c9cd9a3
Merge branch 'master' of https://github.com/mjk22071998/C-Plus-Plus
mjk22071998 6c8305b
Merge branch 'master' into master
realstealthninja cffb85a
Merge branch 'master' into master
realstealthninja 481e5db
Merge branch 'TheAlgorithms:master' into master
mjk22071998 9772468
initial commit of Binary Addition
mjk22071998 8461184
"Formatting changes and whitespace adjustments in binary_addition.cpp"
mjk22071998 c846d8b
Documentation added
mjk22071998 47685a5
fix: removed unnecessary whitespaces
mjk22071998 d9113db
Merge branch 'TheAlgorithms:master' into master
mjk22071998 206758b
Merge branch 'master' into master
mjk22071998 e62242e
fix: Fixed the case of non binary strings
mjk22071998 5236bd0
Merge branch 'master' of https://github.com/mjk22071998/C-Plus-Plus
mjk22071998 b172e05
clang linted
mjk22071998 19dc886
Merge branch 'master' into master
mjk22071998 aece5a2
docs: Documentation updated
mjk22071998 592c0d9
Comments updated
mjk22071998 074583a
Merge branch 'master' into master
mjk22071998 12d0b29
Removed link
mjk22071998 cd8a595
Merge branch 'master' into master
mjk22071998 e0fc3d8
clang-format and clang-tidy fixes for cd8a5953
github-actions[bot] 916ead7
made `tests()` static
mjk22071998 3f07ca4
added @returns in documentation of tests function
mjk22071998 d039369
added @return in documentation of main function
mjk22071998 b3e829e
Merge branch 'master' into master
mjk22071998 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
/** | ||
* @file binary_addition.cpp | ||
* @brief Adds two binary numbers and outputs resulting string | ||
* @see https://www.geeksforgeeks.org/cpp-program-to-add-two-binary-strings/ | ||
mjk22071998 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
* @details 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. | ||
* @author [Muhammad Junaid Khalid](https://github.com/mjk22071998) | ||
*/ | ||
|
||
#include <algorithm> /// for reverse function | ||
#include <cassert> /// for tests | ||
#include <iostream> /// for input and outputs | ||
#include <string> /// for string class | ||
|
||
/** | ||
* @namespace | ||
* @brief Greedy Algorithms | ||
*/ | ||
namespace greedy_algorithms { | ||
/** | ||
* A class to perform binary addition of two binary strings. | ||
mjk22071998 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
*/ | ||
class BinaryAddition { | ||
public: | ||
/** | ||
* Adds two binary strings and returns the result as a binary string. | ||
* | ||
* @param a The first binary string. | ||
* @param b The second binary string. | ||
* @return The sum of the two binary strings as a binary string, or an empty | ||
* string if either input string contains non-binary characters. | ||
*/ | ||
std::string addBinary(const std::string& a, const std::string& b) { | ||
if (!isValidBinaryString(a) || !isValidBinaryString(b)) { | ||
return ""; // Return empty string if input contains non-binary | ||
// characters | ||
} | ||
|
||
std::string result; | ||
int carry = 0; | ||
int maxLength = std::max(a.size(), b.size()); | ||
|
||
// Traverse both strings from the end to the beginning | ||
for (int i = 0; i < maxLength; ++i) { | ||
// Get the current bits from both strings, if available | ||
int bitA = (i < a.size()) ? (a[a.size() - 1 - i] - '0') : 0; | ||
int bitB = (i < b.size()) ? (b[b.size() - 1 - i] - '0') : 0; | ||
|
||
// Calculate the sum of bits and carry | ||
int sum = bitA + bitB + carry; | ||
carry = sum / 2; // Determine the carry for the next bit | ||
result.push_back((sum % 2) + | ||
'0'); // Append the sum's current bit to result | ||
} | ||
if (carry) { | ||
result.push_back('1'); | ||
} | ||
std::reverse(result.begin(), result.end()); | ||
return result; | ||
} | ||
|
||
private: | ||
/** | ||
* Validates whether a string contains only binary characters (0 or 1). | ||
* @param str The string to validate. | ||
* @return true if the string is binary, false otherwise. | ||
*/ | ||
bool isValidBinaryString(const std::string& str) const { | ||
return std::all_of(str.begin(), str.end(), | ||
[](char c) { return c == '0' || c == '1'; }); | ||
} | ||
}; | ||
} // namespace greedy_algorithms | ||
|
||
/** | ||
* Function to run tests for the addBinary method. | ||
*/ | ||
void tests() { | ||
mjk22071998 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
greedy_algorithms::BinaryAddition binaryAddition; | ||
|
||
// Valid binary string tests | ||
assert(binaryAddition.addBinary("1010", "1101") == "10111"); | ||
assert(binaryAddition.addBinary("1111", "1111") == "11110"); | ||
realstealthninja marked this conversation as resolved.
Show resolved
Hide resolved
|
||
assert(binaryAddition.addBinary("101", "11") == "1000"); | ||
assert(binaryAddition.addBinary("0", "0") == "0"); | ||
assert(binaryAddition.addBinary("1111", "1111") == "11110"); | ||
assert(binaryAddition.addBinary("0", "10101") == "10101"); | ||
assert(binaryAddition.addBinary("10101", "0") == "10101"); | ||
assert(binaryAddition.addBinary("101010101010101010101010101010", | ||
"110110110110110110110110110110") == | ||
"1100001100001100001100001100000"); | ||
assert(binaryAddition.addBinary("1", "11111111") == "100000000"); | ||
assert(binaryAddition.addBinary("10101010", "01010101") == "11111111"); | ||
|
||
// Invalid binary string tests (should return empty string) | ||
assert(binaryAddition.addBinary("10102", "1101") == ""); | ||
assert(binaryAddition.addBinary("ABC", "1101") == ""); | ||
assert(binaryAddition.addBinary("1010", "1102") == ""); | ||
assert(binaryAddition.addBinary("111", "1x1") == ""); | ||
assert(binaryAddition.addBinary("1x1", "111") == ""); | ||
assert(binaryAddition.addBinary("1234", "1101") == ""); | ||
} | ||
|
||
/** | ||
* Main function to execute the program. | ||
mjk22071998 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
*/ | ||
int main() { | ||
tests(); | ||
mjk22071998 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
std::cout << "All tests passed.\n"; | ||
return 0; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.