-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleet202568..cpp
More file actions
29 lines (29 loc) · 825 Bytes
/
leet202568..cpp
File metadata and controls
29 lines (29 loc) · 825 Bytes
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
class Solution {
public:
int minMaxDifference(int num) {
string str = to_string(num);
string ma = "";
string mi = "";
int n = str.size();
char ele = ' ';
// Step 1: Find first non-9 digit for max replacement
for(int i=0;i<n;i++){
if(str[i] != '9'){
ele = str[i];
break;
}
}
// Step 2: Replace that digit with 9 for max
for(int i=0;i<n;i++){
if(ele == str[i]) ma += '9';
else ma += str[i];
}
// Step 3: Replace first digit for min with 0
for(int i=0;i<n;i++){
if(str[0] == str[i]) mi += '0';
else mi += str[i];
}
// Step 4: Convert and calculate result
return stoi(ma) - stoi(mi);
}
};