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, 108]
只交换一次整数中的两个数,获得最大的值
思路:从高位向低扫描,如果后面某位的数大于等于当前位的值,交换位置后即得到最大值。
1 public int maximumSwap(int num) { 2 // 从高位向低扫描,如果后面某位的数大于等于当前位的值,交换位置后即得到最大值 3 char[] dig = String.valueOf(num).toCharArray(); 4 int maxIndex = 0; 5 while (maxIndex < dig.length - 1) { 6 int newMaxIndex = maxIndex; 7 for (int i = maxIndex + 1; i < dig.length; i++) { 8 if (dig[newMaxIndex] <= dig[i]) newMaxIndex = i; 9 } 10 if (newMaxIndex != maxIndex && dig[newMaxIndex] != dig[maxIndex]) { 11 char temp = dig[newMaxIndex]; 12 dig[newMaxIndex] = dig[maxIndex]; 13 dig[maxIndex] = temp; 14 return Integer.valueOf(new String(dig)); 15 }else maxIndex++;//当前maxIndex的后面没有大于等于它的数字了 16 } 17 return num; 18 }