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
Approach
Java
public class MaximumSwap {public static void main(String[] args) {int n = 2736;System.out.println(maximumSwap(n));}static int maximumSwap(int num) {char[] str = String.valueOf(num).toCharArray();for (int i = 0; i < str.length; i++) {char m = str[i];int flag = 0;int pos = 0;for (int j = str.length - 1; j > i; j--) {if (str[j] > m) {m = str[j];pos = j;flag = 1;}}if (flag == 1) {char temp = str[pos];str[pos] = str[i];str[i] = temp;break;}}int ans = Integer.parseInt(new String(str));return ans;}}
C++
#include <bits/stdc++.h>using namespace std;int maximumSwap(int num){string str = to_string(num);for (int i = 0; i < str.size(); i++){char m = str[i];int flag = 0;int pos;for (int j = str.size() - 1; j > i; j--){if (str[j] > m){m = str[j];pos = j;flag = 1;}}if (flag == 1){char temp = str[pos];str[pos] = str[i];str[i] = temp;break;}}int ans = stoi(str);return ans;}int main(){int n = 2736;cout << maximumSwap(n);return 0;}
No comments:
Post a Comment