Maximum 69 Number

Let’s work on this problem by taking the integer input, converting it into a string, and then processing each character.

We’ll follow these steps:

  1. Convert the integer number into a string, which makes it easier to manipulate individual digits.
  2. Loop over the characters in the string.
  3. When we encounter the first ‘6’, we change it to ‘9’ and break the loop. This is because the first ‘6’ from the left side contributes to the smallest value among all ‘6’s, changing it to ‘9’ will give us the maximum number.
  4. Convert the string back into an integer and return it.

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def maximum69Number(self, num: int) -> int:
        # Convert the number to a list of characters
        num_str = list(str(num))

        # Iterate over the characters
        for i in range(len(num_str)):
            # If the character is '6', change it to '9' and break the loop
            if num_str[i] == '6':
                num_str[i] = '9'
                break

        # Convert the list of characters back to a number
        return int(''.join(num_str))

This code will replace the first ‘6’ in the number with ‘9’, giving us the maximum possible number we can obtain with a single change.