1 minute read

Problem Statement

leetcode problem link

Brute Force [Accepted]

class Solution:
    def maximum69Number (self, num: int) -> int:
        arr = deque()
        while num > 0:
            x = num % 10
            arr.appendleft(x)
            num = num // 10

        for i, x in enumerate(arr):
            if x == 6:
                arr[i] = 9
                break

        curr = 10 ** (len(arr) - 1)
        res = 0
        for x in arr:
            res = res + x * curr
            curr //= 10
        return res

Editorial

Approach 1: Convert the integer to an iterable object

class Solution:
    def maximum69Number (self, num: int) -> int:
        # Convert the input 'num' to a list of character 'num_char_list'.
        num_char_list = list(str(num))

        # Iterate over the list (from high to low).
        for i, cur_char in enumerate(num_char_list):
            # If we find the first '6', replace it with '9' and break the loop.
            if cur_char == '6':
                num_char_list[i] = '9'
                break

        # Convert the modified char list to integer and return it.
        return int("".join(num_char_list))

Approach 2: Use built-in function

class Solution:
    def maximum69Number (self, num: int) -> int:
        # Convert the input 'num' to the string 'num_string'.
        num_string = str(num)

        # Use the built-in function to replace the first '6' with '9'.
        # Return the integer converted from the modified 'num_string'.
        return int(num_string.replace('6', '9', 1))

Approach 3: Check the remainder

class Solution:
    def maximum69Number (self, num: int) -> int:
        # Since we start with the lowest digit, initialize curr_digit = 0.
        curr_digit = 0
        index_first_six = -1
        num_copy = num

        # Check every digit of 'num_copy' from low to high.
        while num_copy:
            # If the current digit is '6', record it as the highest digit of 6.
            if num_copy % 10 == 6:
                index_first_six = curr_digit

            # Move on to the next digit.
            num_copy //= 10
            curr_digit += 1

        # If we don't find any digit of '6', return the original number,
        # otherwise, increment 'num' by the difference made by the first '6'.
        return num if index_first_six == -1 else num + 3 * 10 ** index_first_six