You are given an integer num
. The num
is represented in the form of a string. Your task is to find the maximum possible difference you can get by changing one single digit of num
to any other digit (0-9). You must ensure the number remains valid after the change (i.e., it must not have any leading zeros unless the number itself is zero).
num
guaranteed to not have leading zeros (except for when num
itself is zero)?
num
itself is zero.num
itself is zero?
num
is zero, then any remapping would lead to the same result as no other number is smaller than zero but zero itself; hence the maximum difference will be zero.num
is always a positive integer.def maxDifferenceByRemappingDigit(num: str) -> int:
# Calculate highest possible number by changing some digit to 9
highest_num = list(num)
for i in range(len(num)):
if num[i] != '9':
high_digit = num[i]
break
highest_num = "".join(['9' if x == high_digit else x for x in num])
# Calculate lowest possible number by changing some digit to 0 or 1
lowest_num = list(num)
if num[0] != '1':
for i in range(len(num)):
if num[i] != '1':
low_digit = num[i]
break
lowest_num = num[0] + "".join(['0' if x == low_digit else x for x in num[1:]])
else:
for i in range(1, len(num)):
if num[i] != '0' and num[i] != '1':
low_digit = num[i]
break
lowest_num = "".join(['0' if x == low_digit else x for x in num])
# Convert strings back to integers
highest_num = int(highest_num)
lowest_num = int(lowest_num)
# Return the maximum difference
return highest_num - lowest_num
# Example usage:
num = "123456"
print(maxDifferenceByRemappingDigit(num)) # Output will be the maximum difference
n
is the length of the number string. The primary operations such as finding the first non-9 digit and replacing digits in the string take linear time relative to the number of digits.Feel free to reach out if you have any more questions or need further clarifications!
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?