题目
Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.
Example 1:
Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:
Input: 9973
Output: 9973
Explanation: No swap.
Note:
The given number is in the range [0, 10^8]
答案
class Solution {
private void s_swap(StringBuilder sb, int i, int j) {
char t = sb.charAt(i);
sb.setCharAt(i, sb.charAt(j));
sb.setCharAt(j, t);
}
public int maximumSwap(int num) {
StringBuilder sb = new StringBuilder(Integer.toString(num));
String max = sb.toString();
for(int i = 0; i < sb.length(); i++) {
for(int j = 0; j < sb.length(); j++) {
if(i == j) continue;
s_swap(sb, i, j);
String t = sb.toString();
if(t.compareTo(max) > 0) {
max = t;
}
s_swap(sb, i, j);
}
}
return Integer.parseInt(max);
}
}