[LeetCode] Max Difference You Can Get From Changing an Integer

1432. Max Difference You Can Get From Changing an Integer

You are given an integer num. You will apply the following steps exactly two times:

  • Pick a digit x (0 <= x <= 9).
  • Pick another digit y (0 <= y <= 9). The digit y can be equal to x.
  • Replace all the occurrences of x in the decimal representation of num by y.
  • The new integer cannot have any leading zeros, also the new integer cannot be 0.

Let a and b be the results of applying the operations to num the first and second times, respectively.

Return the max difference between a and b.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int maxDiff(int num) {
int ma = num, mi = num;
string u = to_string(num);
for(char f = '0'; f <= '9'; f++) {
for(char t = '0'; t <= '9'; t++) {
if(u[0] == f and t == '0') continue;
if(f == t) continue;
string now = u;
for(int i = 0; i < now.length(); i++) {
if(now[i] == f) now[i] = t;
}
ma = max(ma, stoi(now));
mi = min(mi, stoi(now));
}
}

return ma - mi;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/22/PS/LeetCode/max-difference-you-can-get-from-changing-an-integer/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.