2704 - Maximum Difference by Remapping a Digit
description
You are given an integer num
. You know that Bob will sneakily remap one of the 10
possible digits (0
to 9
) to another digit.
Return the difference between the maximum and minimum values Bob can make by remapping exactly one digit in num
.
Notes:
- When Bob remaps a digit d1 to another digit d2, Bob replaces all occurrences of
d1
innum
withd2
. - Bob can remap a digit to itself, in which case
num
does not change. - Bob can remap different digits for obtaining minimum and maximum values respectively.
- The resulting number after remapping can contain leading zeroes.
Example 1:
Input: num = 11891 Output: 99009 Explanation: To achieve the maximum value, Bob can remap the digit 1 to the digit 9 to yield 99899. To achieve the minimum value, Bob can remap the digit 1 to the digit 0, yielding 890. The difference between these two numbers is 99009.
Example 2:
Input: num = 90 Output: 99 Explanation: The maximum value that can be returned by the function is 99 (if 0 is replaced by 9) and the minimum value that can be returned by the function is 0 (if 9 is replaced by 0). Thus, we return 99.
Constraints:
1 <= num <= 108
submission
impl Solution {
// max value after remap: remap the first non-9 digit to 9
// min value after remap: remap the first digit to 0
pub fn min_max_difference(num: i32) -> i32 {
let remap = |mut num: i32, o: i32, r: i32| {
let mut ans = 0;
let mut weight = 1;
while num > 0 {
ans += weight * if num % 10 == o { r } else { num % 10 };
num /= 10;
weight *= 10;
}
ans
};
let first_digit = |mut num: i32| {
while num >= 10 {
num /= 10;
}
num
};
let first_non_nine_digit = |mut num: i32| {
let mut digit = 0;
while num > 0 {
if num % 10 != 9 {
digit = num % 10;
}
num /= 10;
}
digit
};
remap(num, first_non_nine_digit(num), 9) - remap(num, first_digit(num), 0)
}
}