Skip to content

Commit

Permalink
Largest Number After Digit Swaps by Parity
Browse files Browse the repository at this point in the history
  • Loading branch information
hikjik committed Oct 19, 2023
1 parent 83809f8 commit c56fb6a
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_catch(test_largest_number_after_digit_swaps_by_parity test.cpp)
33 changes: 33 additions & 0 deletions solutions/largest-number-after-digit-swaps-by-parity/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#pragma once

#include <queue>
#include <vector>

class Solution {
public:
static int largestInteger(int num) {
const auto digits = getDigits(num);

std::vector<std::priority_queue<int>> 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<int> getDigits(int n) {
std::vector<int> digits;
for (int i = n; i; i /= 10) {
digits.push_back(i % 10);
}
std::reverse(digits.begin(), digits.end());
return digits;
}
};
26 changes: 26 additions & 0 deletions solutions/largest-number-after-digit-swaps-by-parity/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#include <catch.hpp>

#include <solution.hpp>

TEST_CASE("Simple") {
struct TestCase {
int num;
int expected;
};

std::vector<TestCase> 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);
}
}

0 comments on commit c56fb6a

Please sign in to comment.