Skip to content

Commit fde22e6

Browse files
Merge pull request #234 from majvax/fix-snippet
[Snippets-C++] fix a snippets and update another.
2 parents d4e8c01 + 4eb004f commit fde22e6

File tree

3 files changed

+31
-28
lines changed

3 files changed

+31
-28
lines changed

snippets/cpp/bit-manipulation/find-non-repeating-number.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@ author: ashukr07
66
---
77

88
```cpp
9-
int find_non_repeating(const std::vector<int>& nums) {
9+
#include <vector>
10+
11+
int find_non_repeating(const std::vector<int> nums) {
1012
int result = 0;
11-
for (int num : nums) {
13+
for (const int num : nums) {
1214
result ^= num;
1315
}
1416
return result;
@@ -17,4 +19,4 @@ int find_non_repeating(const std::vector<int>& nums) {
1719
// Usage:
1820
std::vector<int> nums = {4, 1, 2, 1, 2};
1921
find_non_repeating(nums); // Returns: 4
20-
```
22+
```

snippets/cpp/math-and-numbers/binary-to-decimal-conversion.md

Lines changed: 0 additions & 25 deletions
This file was deleted.
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
---
2+
title: Binary to Unsigned Integer Conversion
3+
description: Converts a binary number represented as a string to its decimal equivalent.
4+
tags: binary, conversion, c++20
5+
author: ashukr07
6+
contributor: majvax
7+
---
8+
9+
```cpp
10+
#include <string>
11+
#include <bitset>
12+
#include <stdexcept>
13+
14+
template <std::unsigned_integral T>
15+
T binary_to_uintegral(const std::string& binary) {
16+
if (binary.size() > sizeof(T) * 8)
17+
throw std::invalid_argument("binary string is too long");
18+
return static_cast<T>(std::bitset<sizeof(T) * 8>(binary).to_ullong());
19+
}
20+
21+
// Usage:
22+
std::string binary(64, '1'); // Binary 8 bytes long with all bits set to 1
23+
binary_to_uintegral<unsigned long long>(binary); // Returns: 18446744073709551615
24+
binary_to_uintegral<long long>(binary); // Compiles error: signed/unsigned mismatch
25+
binary_to_uintegral<unsigned long long>(std::string(65, '1')); // Throws: std::invalid_argument
26+
```

0 commit comments

Comments
 (0)