---
# System prepended metadata

title: 2566. Maximum Difference by Remapping a Digit
tags: [Leetcode]

---

<style>
    html, body, .ui-content {
    background: #222222;
    color: #00BFFF;
}
::-webkit-scrollbar {
    width: 10px;
}
::-webkit-scrollbar-track {
    background: transparent;
}
::-webkit-scrollbar-thumb {
    background: linear-gradient(180deg, #2BE8CF60 0%, #2B83E860 100%);
    border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
    background: linear-gradient(180deg, #2BE8CF95 0%, #2B83E895 100%);
}
    /* 設定 code 模板 */
    .markdown-body code,
.markdown-body tt {
    background-color: #ffffff36;
}
.markdown-body .highlight pre,
.markdown-body pre {
    color: #ddd;
    background-color: #00000036;
}
.hljs-tag {
    color: #ddd;
}
.token.operator {
  background-color: transparent;
}
   
</style>

###### tags: `Leetcode`

# 2566. Maximum Difference by Remapping a Digit


###### Link : https://leetcode.com/problems/maximum-difference-by-remapping-a-digit/

## 題目
1. When Danny remaps a digit d1 to another digit d2, Danny replaces all occurrences of d1 in num with d2.
2. Danny can remap a digit to itself, in which case num does not change.
3. Danny can remap different digits for obtaining minimum and maximum values respectively.
4. The resulting number after remapping can contain leading zeroes.
## 程式碼

```cpp=
class Solution {
public:
    int minMaxDifference(int num) {
        string biggest = to_string(num), smallest = biggest;
        const int n = biggest.size();
        char leading = 0, leading2 = smallest[0];
        for(int i = 0;i < n;++i){
            if(leading == 0 && biggest[i] != '9'){
                leading = biggest[i];
                biggest[i] = '9';
            }
            else if(biggest[i] == leading)
                biggest[i] = '9';
            if(smallest[i] == leading2)
                smallest[i] = '0';
        }
        return stoi(biggest) - stoi(smallest);
    }
};
```