diff --git a/snippets/cpp/bit-manipulation/find-non-repeating-number.md b/snippets/cpp/bit-manipulation/find-non-repeating-number.md index 1195587d..60f322bb 100644 --- a/snippets/cpp/bit-manipulation/find-non-repeating-number.md +++ b/snippets/cpp/bit-manipulation/find-non-repeating-number.md @@ -6,9 +6,11 @@ author: ashukr07 --- ```cpp -int find_non_repeating(const std::vector& nums) { +#include + +int find_non_repeating(const std::vector nums) { int result = 0; - for (int num : nums) { + for (const int num : nums) { result ^= num; } return result; @@ -17,4 +19,4 @@ int find_non_repeating(const std::vector& nums) { // Usage: std::vector nums = {4, 1, 2, 1, 2}; find_non_repeating(nums); // Returns: 4 -``` \ No newline at end of file +``` diff --git a/snippets/cpp/math-and-numbers/binary-to-decimal-conversion.md b/snippets/cpp/math-and-numbers/binary-to-decimal-conversion.md deleted file mode 100644 index b2a607cb..00000000 --- a/snippets/cpp/math-and-numbers/binary-to-decimal-conversion.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Binary to Decimal Conversion -description: Converts a binary number represented as a string to its decimal equivalent. -tags: binary, conversion -author: ashukr07 ---- - -```cpp -int binary_to_decimal(const std::string& binary) { - int decimal = 0; - int base = 1; // Base value for the least significant bit - - for (int i = binary.length() - 1; i >= 0; --i) { - if (binary[i] == '1') { - decimal += base; - } - base *= 2; // Move to the next power of 2 - } - return decimal; -} - -// Usage: -std::string binary = "1011"; // Binary representation of 11 -binary_to_decimal(binary); // Returns: 11 -``` \ No newline at end of file diff --git a/snippets/cpp/math-and-numbers/binary-to-unsigned-integer-conversion.md b/snippets/cpp/math-and-numbers/binary-to-unsigned-integer-conversion.md new file mode 100644 index 00000000..b5ab1a8d --- /dev/null +++ b/snippets/cpp/math-and-numbers/binary-to-unsigned-integer-conversion.md @@ -0,0 +1,26 @@ +--- +title: Binary to Unsigned Integer Conversion +description: Converts a binary number represented as a string to its decimal equivalent. +tags: binary, conversion, c++20 +author: ashukr07 +contributor: majvax +--- + +```cpp +#include +#include +#include + +template +T binary_to_uintegral(const std::string& binary) { + if (binary.size() > sizeof(T) * 8) + throw std::invalid_argument("binary string is too long"); + return static_cast(std::bitset(binary).to_ullong()); +} + +// Usage: +std::string binary(64, '1'); // Binary 8 bytes long with all bits set to 1 +binary_to_uintegral(binary); // Returns: 18446744073709551615 +binary_to_uintegral(binary); // Compiles error: signed/unsigned mismatch +binary_to_uintegral(std::string(65, '1')); // Throws: std::invalid_argument +```