Yes, there is a simpler way to achieve the same result. The goal is to maximize the number by replacing one digit with '9' and minimize the number by replacing one digit with '0' (or '1' if the first digit is '1'). Here's a more concise version of your code:
Simplified Solution:
class Solution:
def maxDiff(self, num: int) -> int:
s = str(num)
# Maximize the number by replacing the first non-'9' digit with '9'
max_num = int(s.replace(s[0] if s[0] != '9' else s[1] if len(s) > 1 else '9', '9') if '9' not in s else s)
# Minimize the number by replacing the first digit with '1' if it's not '1', else replace the first non-'0' and non-'1' digit with '0'
if s[0] != '1':
min_num = int(s.replace(s[0], '1'))
else:
for c in s[1:]:
if c not in ('0', '1'):
min_num = int(s.replace(c, '0'))
break
else:
min_num = num
return max_num - min_num
Even Simpler Approach:
We can further simplify the logic by directly finding the first digit to replace for both the maximum and minimum cases:
class Solution:
def maxDiff(self, num: int) -> int:
s = str(num)
# For max_num: replace the first non-'9' digit with '9'
for i, c in enumerate(s):
if c != '9':
max_num = int(s[:i] + '9' + s[i+1:])
break
else:
max_num = num
# For min_num: replace the first digit with '1' if it's not '1', else replace the first non-'0' and non-'1' digit with '0'
if s[0] != '1':
min_num = int('1' + s[1:])
else:
for i in range(1, len(s)):
if s[i] not in ('0', '1'):
min_num = int(s[:i] + '0' + s[i+1:])
break
else:
min_num = num
return max_num - min_num
Explanation:
-
Maximizing the Number (max_num):
- Iterate through each digit of the number. The first digit that is not '9' is replaced with '9' to get the maximum possible number. If all digits are '9', the number remains unchanged.
-
Minimizing the Number (min_num):
- If the first digit is not '1', replace it with '1' to get the smallest possible number.
- If the first digit is '1', look for the first subsequent digit that is not '0' or '1' and replace it with '0'. If no such digit is found, the number remains unchanged.
This approach avoids unnecessary replacements and directly constructs the desired numbers by focusing on the first relevant digit.