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 in num with d2.
- 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.
출처:https://leetcode.com/problems/maximum-difference-by-remapping-a-digit/description/
풀이
function minMaxDifference(num: number): number {
let str = num.toString();
let min_digit = str[0];
let min_value = parseInt(str.replaceAll(min_digit,"0"));
let arr = str.split('');
let max_start =arr.findIndex(x=>parseInt(x) < 9);
let max_digit = str[max_start];
let max_value = parseInt(str.replaceAll(max_digit,"9"));
return max_value - min_value
};
- 숫자 변환의 범위: 숫자는 0부터 9까지로 제한
- 변환 규칙:
- Bob은 숫자 d1을 d2로 변환.
- d1을 d2로 변환할 때, num에 있는 모든 d1을 d2로 바꿈
- Bob은 숫자를 자기 자신으로 변환할 수도 있음. 이 경우 num은 변하지 않음.
- 최대값을 얻기 위해 한 가지 방식으로 변환하고, 최소값을 얻기 위해 다른 방식으로 변환할 수 있음
예시 실행
예를 들어 num이 11891일 때:
- 최소값은 1을 0으로 변환하여 890
- 최대값은 1을 9로 변환하여 99899
- 따라서 minMaxDifference(11891)는 99899 - 890 = 99009
이 함수는 주어진 숫자에서 가능한 최대값과 최소값을 찾아 그 차이를 반환하는 방식으로 작동
'LeetCode' 카테고리의 다른 글
| 589. N-ary Tree Preorder Traversal / TypeScript (1) | 2024.06.01 |
|---|---|
| 2629. Function Composition / TypeScript (0) | 2024.05.31 |
| 2293. Min Max Game / TypeScript (0) | 2024.05.29 |
| 938. Range Sum of BST / TypeScript (0) | 2024.05.28 |
| 3038. Maximum Number of Operations With the Same Score I / TypeScript (0) | 2024.05.27 |