Skip to content

Commit

Permalink
fix a snippets and update another.
Browse files Browse the repository at this point in the history
  • Loading branch information
majvax committed Jan 13, 2025
1 parent 88d7805 commit b58e3ea
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 27 deletions.
6 changes: 4 additions & 2 deletions snippets/cpp/bit-manipulation/find-non-repeating-number.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ author: ashukr07
---

```cpp
#include <vector>

int find_non_repeating(const std::vector<int>& nums) {
int result = 0;
for (int num : nums) {
for (const int num : nums) {
result ^= num;
}
return result;
Expand All @@ -17,4 +19,4 @@ int find_non_repeating(const std::vector<int>& nums) {
// Usage:
std::vector<int> nums = {4, 1, 2, 1, 2};
find_non_repeating(nums); // Returns: 4
```
```
25 changes: 0 additions & 25 deletions snippets/cpp/math-and-numbers/binary-to-decimal-conversion.md

This file was deleted.

Original file line number Diff line number Diff line change
@@ -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 <string>
#include <bitset>
#include <stdexcept>

template <std::unsigned_integral T>
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<T>(std::bitset<sizeof(T) * 8>(binary).to_ullong());
}

// Usage:
std::string binary(64, '1'); // Binary 8 bytes long with all bits set to 1
binary_to_uintegral<unsigned long long>(binary); // Returns: 18446744073709551615
binary_to_uintegral<long long>(binary); // Compiles error: signed/unsigned mismatch
binary_to_uintegral<unsigned long long>(std::string(65, '1')); // Throws: std::invalid_argument
```

0 comments on commit b58e3ea

Please sign in to comment.