You are given a positive integer num consisting only of digits 6 and 9.
Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).
Example 1:
Input: num = 9669
Output: 9969
Explanation:
Changing the first digit results in 6669.
Changing the second digit results in 9969.
Changing the third digit results in 9699.
Changing the fourth digit results in 9666.
The maximum number is 9969.
Plain Text
복사
Example 2:
Input: num = 9996
Output: 9999
Explanation: Changing the last digit 6 to 9 results in the maximum number.
Plain Text
복사
Example 3:
Input: num = 9999
Output: 9999
Explanation: It is better not to apply any change.
Plain Text
복사
Constraints:
•
1 <= num <= 104
•
num consists of only 6 and 9 digits.
To avoid repeating previous mistakes, beginning this time I will read the problem thoroughly and ensure I fully understand the requirements before starting.
When I read the problem, it seems to ask for the largest number among all possibilities that can be obtained by changing at most one digit in the given number num. The digit can only be changed from 6 → 9 or 9 → 6.
My approach is to loop through num, change the digit at each index, and append the resulting value to a newly created array. After the loop finishes, I plan to return the maximum value from that array.
First Try
class Solution:
def maximum69Number (self, num: int) -> int:
# If given number num contains only 9
if all(v =='9' for v in str(num)):
return num
lst = []
for i,v in enumerate(str(num)):
n = list(str(num))
if v == '9':
n[i] = '6'
lst.append(''.join(n))
else:
n[i] = '9'
lst.append(''.join(n))
return max([int(v) for v in lst])
Python
복사
First, if the given num is composed only of 9s, there’s nothing to compare—it’s already the largest, so return it as is. Otherwise, loop through num, flip the digit at each index, and store the resulting number in lst. After all iterations finish, return the largest value in lst.
The test cases passed. I’ll go ahead and submit the solution.
Fortunately, my solution was accepted on the first try. It really seems that the right approach is to read the problem carefully, understand exactly what it’s asking for, and then write the code.