We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Maximum 69 Number

Difficulty: Easy


Problem Description

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).


Key Insights

  • The problem requires us to maximize a number by altering a single digit.
  • Changing a '6' to a '9' will always increase the value of the number.
  • If the number consists only of '9's, any change will decrease the value, hence no change is needed.
  • The first occurrence of '6' should be changed to '9' to achieve the maximum value.

Space and Time Complexity

Time Complexity: O(n), where n is the number of digits in num. Space Complexity: O(1), as we are using a constant amount of space.


Solution

To solve the problem, we can convert the number to a string to easily manipulate its digits. We will iterate through the string representation of the number and look for the first occurrence of the digit '6'. Once found, we change it to '9' and return the new number. If there are no '6's, we return the number as is since it is already maximized.


Code Solutions

def maximum69Number (num: int) -> int:
    # Convert the number to a string to manipulate digits
    num_str = str(num)
    
    # Find the first occurrence of '6' and change it to '9'
    for i in range(len(num_str)):
        if num_str[i] == '6':
            # Change the first '6' to '9' and break the loop
            num_str = num_str[:i] + '9' + num_str[i+1:]
            break
            
    # Convert back to an integer and return
    return int(num_str)
← Back to All Questions