Topics
Given a non-negative integer, you could swap both 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]
Swap only two digits in an integer to get the maximum value idea
Scan from high to low, if the number of subsequent bits is greater than the value of the current bit, the maximum value is obtained after the swap position. Code
class Solution {public:///integer array to int int toint (int* arr, int n) {int res = 0;
for (int i=0; i<n; i++) {res = res*10 + arr[i];
} return res;
} int maximumswap (int num) {/////First get array of each digit int arr[20] = {0};
int back = num, n = 0;
while (back) {arr[n++] = back% 10;
Back/= 10;
} for (int i=0, j=n-1; i<j; i++, j--) swap (Arr[i], arr[j]);
Scan from high to low for (int i=0; i<n; i++) {int maxn = arr[i];
int index = i;
for (int j=i+1; j<n; J + +) {if (Arr[j] >= maxn) {index = j;
MAXN = Arr[j];
}} if (Maxn > Arr[i]) {swap (Arr[i], arr[index]);
Return ToInt (arr, n);
}} return num;
}
};