DEV Community

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

Posted on • Originally published at leandrotk.github.io

1 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay