Largest Number After Digit Swaps by Parity LeetCode solution in C++

1
class Solution {
2
public:
3
int largestInteger(int num) {
4
priority_queue<int> p; // priority queue to store odd digits in descending order
5
priority_queue<int> q; // priority queue to store even digits in descending order
6
string nums = to_string(num); // converting num to a string for easy access of the digits
7
int n = nums.size(); // n stores the number of digits in num
8

9
for (int i = 0; i < n; i++) {
10
int digit = nums[i] - '0';
11
if ((digit) % 2) // if digit is odd, push it into priority queue p
12
p.push(digit);
13
else
14
q.push(digit); // if digit is even, push it into priority queue q
15
}
16

17
int answer = 0;
18
for (int i = 0; i < n; i++) {
19
answer = answer * 10;
20
if ((nums[i] - '0') % 2) // if the digit is odd, add the largest odd digit
21
// of p into the answer
22
{
23
answer += p.top();
24
p.pop();
25
} else {
26
answer += q.top();
27
q.pop();
28
} // if the digit is even, add the largest even digit of q into the answer
29
}
30
return answer;
31
}
32
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0