diff --git a/CMakeLists.txt b/CMakeLists.txt index d7bcfff7..069cfaff 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -322,6 +322,7 @@ add_task(kth-smallest-element-in-a-bst) add_task(largest-3-same-digit-number-in-string) add_task(largest-color-value-in-a-directed-graph) add_task(largest-local-values-in-a-matrix) +add_task(largest-number-after-digit-swaps-by-parity) add_task(largest-perimeter-triangle) add_task(largest-positive-integer-that-exists-with-its-negative) add_task(largest-rectangle-in-histogram) diff --git a/solutions/largest-number-after-digit-swaps-by-parity/CMakeLists.txt b/solutions/largest-number-after-digit-swaps-by-parity/CMakeLists.txt new file mode 100644 index 00000000..fd490573 --- /dev/null +++ b/solutions/largest-number-after-digit-swaps-by-parity/CMakeLists.txt @@ -0,0 +1 @@ +add_catch(test_largest_number_after_digit_swaps_by_parity test.cpp) diff --git a/solutions/largest-number-after-digit-swaps-by-parity/solution.hpp b/solutions/largest-number-after-digit-swaps-by-parity/solution.hpp new file mode 100644 index 00000000..3bffbbab --- /dev/null +++ b/solutions/largest-number-after-digit-swaps-by-parity/solution.hpp @@ -0,0 +1,33 @@ +#pragma once + +#include +#include + +class Solution { +public: + static int largestInteger(int num) { + const auto digits = getDigits(num); + + std::vector> heaps(2); + for (auto digit : digits) { + heaps[digit & 1].push(digit); + } + + int ans = 0; + for (auto digit : digits) { + ans = ans * 10 + heaps[digit & 1].top(); + heaps[digit & 1].pop(); + } + return ans; + } + +private: + static std::vector getDigits(int n) { + std::vector digits; + for (int i = n; i; i /= 10) { + digits.push_back(i % 10); + } + std::reverse(digits.begin(), digits.end()); + return digits; + } +}; diff --git a/solutions/largest-number-after-digit-swaps-by-parity/test.cpp b/solutions/largest-number-after-digit-swaps-by-parity/test.cpp new file mode 100644 index 00000000..ef2cdb29 --- /dev/null +++ b/solutions/largest-number-after-digit-swaps-by-parity/test.cpp @@ -0,0 +1,26 @@ +#include + +#include + +TEST_CASE("Simple") { + struct TestCase { + int num; + int expected; + }; + + std::vector test_cases{ + { + .num = 1234, + .expected = 3412, + }, + { + .num = 65875, + .expected = 87655, + }, + }; + + for (const auto &[num, expected] : test_cases) { + const auto actual = Solution::largestInteger(num); + REQUIRE(expected == actual); + } +}