forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
_1432.java
85 lines (82 loc) · 3.23 KB
/
_1432.java
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.fishercoder.solutions;
public class _1432 {
public static class Solution1 {
public int maxDiff(int num) {
int smallest = getSmallest(num);
int biggest = getBiggest(num);
return biggest - smallest;
}
private int getBiggest(int num) {
int firstDigit = Integer.parseInt(Integer.toString(num).substring(0, 1));
if (firstDigit == 9) {
String remainder = Integer.toString(num).substring(1);
int numberToChangeToNine = 0;
for (char c : remainder.toCharArray()) {
if (c == '9') {
continue;
} else {
numberToChangeToNine = Integer.parseInt("" + c);
break;
}
}
StringBuilder sb = new StringBuilder();
sb.append('9');
for (char c : remainder.toCharArray()) {
if (Integer.parseInt(c + "") == numberToChangeToNine) {
sb.append("9");
} else {
sb.append(c);
}
}
return Integer.parseInt(sb.toString());
} else {
int numberToChangeToNine = firstDigit;
StringBuilder sb = new StringBuilder();
for (char c : Integer.toString(num).toCharArray()) {
if (Integer.parseInt("" + c) == numberToChangeToNine) {
sb.append("9");
} else {
sb.append(c);
}
}
return Integer.parseInt(sb.toString());
}
}
private int getSmallest(int num) {
int firstDigit = Integer.parseInt(Integer.toString(num).substring(0, 1));
if (firstDigit == 1) {
String remainder = Integer.toString(num).substring(1);
int numberToChangeToZero = 0;
for (char c : remainder.toCharArray()) {
if (c == '0' || c == '1') {
continue;
} else {
numberToChangeToZero = Integer.parseInt("" + c);
break;
}
}
StringBuilder sb = new StringBuilder();
sb.append('1');
for (char c : remainder.toCharArray()) {
if (Integer.parseInt(c + "") == numberToChangeToZero) {
sb.append("0");
} else {
sb.append(c);
}
}
return Integer.parseInt(sb.toString());
} else {
int numberToChangeToOne = firstDigit;
StringBuilder sb = new StringBuilder();
for (char c : Integer.toString(num).toCharArray()) {
if (Integer.parseInt("" + c) == numberToChangeToOne) {
sb.append("1");
} else {
sb.append(c);
}
}
return Integer.parseInt(sb.toString());
}
}
}
}