-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC670.java
More file actions
47 lines (39 loc) · 1.13 KB
/
LC670.java
File metadata and controls
47 lines (39 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
* LC670
*/
import java.util.*;
public class LC670 {
public static int maximumSwap(int num) {
char numArr[] = Integer.toString(num).toCharArray();
int n = numArr.length;
char maxElem = numArr[n - 1];
int maxIndex = n - 1;
int swapIde1 = -1;
int swapIde2 = -1;
for (int i = n - 1; i >= 0; i--) {
if (numArr[i] > maxElem) {
maxElem = numArr[i];
maxIndex = i;
} else if (numArr[i] < maxElem) {
swapIde1 = i;
swapIde2 = maxIndex;
}
}
// Swapping
if (swapIde1 != -1) {
char temp = numArr[swapIde1];
numArr[swapIde1] = numArr[swapIde2];
numArr[swapIde2] = temp;
}
return Integer.parseInt(new String(numArr));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number here : ");
int n = sc.nextInt();
System.out.println();
int ans = maximumSwap(n);
System.out.println(ans);
sc.close();
}
}