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
48
49
public class SmallestAdjacent {

// first version, convert int x to a string
public static int solutionString(int x){
String input = String.valueOf(x);
int min = Integer.MAX_VALUE;

for (int i = 0; i < input.length() - 1; i++) {
int index = (input.charAt(i) - '0' < input.charAt(i + 1) - '0') ? i : i + 1;
String result = input.substring(0, index) + input.substring(index + 1);
int res = Integer.parseInt(result);
min = res > min ? min : res;
}
return min;
}

public static void main(String[] args) {
System.out.println(solutionString(233614));
}

// second solution, manipulate of a number
public static int solution(int x){
int min = Integer.MAX_VALUE;

// copy the digits to an array
ArrayList<Integer> digits = new ArrayList<>();
int input = x;
while (input > 0) {
digits.add(input % 10);
input /= 10;
}

// for each pair of adjacent digits
for (int i = 0; i < digits.size() - 1; i++) {
int removedIndex = digits.get(i) > digits.get(i + 1) ? i + 1 : i;
int replacedInt = reconstruct(x, removedIndex);
min = replacedInt > min ? min : replacedInt;
}

return min;
}

private static int reconstruct(int x, int removedIndex) {
// this will not overflow since it must be less than the given integer x
int afterPower = (int) Math.pow(10, removedIndex);
// concatenate the digits before and after the removed digit
return x / afterPower / 10 * (int) afterPower + x % afterPower;
}
}