DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Algorithms Problem Solving: Maximum 69 Number
TK
TK

Posted on • Originally published at leandrotk.github.io

Algorithms Problem Solving: Maximum 69 Number

This post is part of the Algorithms Problem Solving series.

Problem description

This is the Maximum 69 Number problem. The description looks like this:

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

Examples

Input: num = 9669
Output: 9969

Input: num = 9996
Output: 9999

Input: num = 9999
Output: 9999
Enter fullscreen mode Exit fullscreen mode

Solution

The idea is to find the first 6 number index in the whole number. And then replace it with 9. That way you get the maximum number.

def maximum_69_number(num):
    six_index = 0
    str_num = str(num)

    for index in range(len(str_num)):
        if str_num[index] == '6':
            six_index = index
            break

    return int(
        str_num[:six_index] +
        '9' +
        str_num[six_index + 1:]
    )
Enter fullscreen mode Exit fullscreen mode

You can also use the replace string method to replace the first 6 number with 9.

'6996'.replace('6', '9', 1)
'9996'

'9696'.replace('6', '9', 1)
'9996'
Enter fullscreen mode Exit fullscreen mode

Resources

Top comments (0)

🌚 Life is too short to browse without dark mode