-
Notifications
You must be signed in to change notification settings - Fork 9
/
MaximumSwap.cpp
51 lines (45 loc) · 1.29 KB
/
MaximumSwap.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Problem: https://leetcode.com/problems/maximum-swap/
#include <vector>
using namespace std;
class MaximumSwap {
public:
int maximumSwap(int num) {
vector<int> digits = getDigits(num);
int num_digits = digits.size();
for (int i = 0; i < num_digits; ++i) {
int max_num = digits[i];
int max_idx = i;
for (int j = num_digits - 1; j > i; --j) {
if (max_num < digits[j]) {
max_num = digits[j];
max_idx = j;
}
}
if (max_idx != i) {
swap(i, max_idx, digits);
return getNum(digits);
}
}
return num;
}
private:
int getNum(vector<int>& digits) {
int sum = 0;
for (int digit : digits) sum = sum * 10 + digit;
return sum;
}
void swap(int i, int j, vector<int>& digits) {
int tmp = digits[i];
digits[i] = digits[j];
digits[j] = tmp;
}
vector<int> getDigits(int num) {
vector<int> digits;
while (num > 0) {
int digit = num - (num / 10) * 10;
digits.insert(digits.begin(), digit);
num = num/10;
}
return digits;
}
};