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
```

## 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:]
)
```

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'
```

## Top comments (0)