670. Maximum Swap

670. Maximum Swap

Description

You are given an integer num. You can swap two digits at most once to get the maximum valued number.

Return the maximum valued number you can get.

Example 1:

1
2
3
Input: num = 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.

Example 2:

1
2
3
Input: num = 9973
Output: 9973
Explanation: No swap.

Constraints:

  • 0 <= num <= 10^8

Hints/Notes

Solution

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int maximumSwap(int num) {
string numStr = to_string(num);
int n = numStr.size();
int max_index = n - 1, p = -1, q = -1;
for (int i = n - 2; i >= 0; i--) {
if (numStr[i] > numStr[max_index]) {
max_index = i;
} else if (numStr[i] < numStr[max_index]) {
p = i;
q = max_index;
}
}
if (p == -1) {
return num;
}
swap(numStr[p], numStr[q]);
return stoi(numStr);
}
};