Teaching Kids Programming – Maximum Number by Inserting Five


Teaching Kids Programming: Videos on Data Structures and Algorithms

Given an integer n, return the maximum number you can make by inserting 5 anywhere in the number.

Example 1
Input
n = 923
Output
9523

Example 2
Input
n = -234
Output
-2345

Example 3
Input
n = 1
Output
51

Hints
Since the length of the number is very small, we can enumarate all possible combinations
…or you can put the 5 into the right spot directly. Positive and negative n can be handled separately. What values should be on the left side of the just inserted 5? Smaller? Greater?

Maximum Number by Inserting Five via Bruteforcing all possible positions

Since the length of the number string is small, we can try all possible positions to insert the five. Note that for negative numbers, we can’t insert 5 before minus sign. We also need to convert integer to string using str function, and use string slicing to get the new number string that has 5 inserted. And finally, we convert string to integer using int function and record the maximum we can get.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def maxNumberByInsertingFive(self, n):
        ans = -math.inf
        s = str(n)
        if n > 0:
            f = 0
        else:
            f = 1  # skip the minus sign
        for i in range(f, len(s) + 1):
            t = s[:i] + '5' + s[i:]
            ans = max(ans, int(t))
        return ans
class Solution:
    def maxNumberByInsertingFive(self, n):
        ans = -math.inf
        s = str(n)
        if n > 0:
            f = 0
        else:
            f = 1  # skip the minus sign
        for i in range(f, len(s) + 1):
            t = s[:i] + '5' + s[i:]
            ans = max(ans, int(t))
        return ans

The initial answer value is set to -math.inf. The time complexity is O(N) and so is space complexity where N is the length of the digits in the number.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
374 words
Last Post: GoLang: Sum of Root To Leaf Binary Numbers via Depth First Search Algorithm
Next Post: GoLang: Check if the Sentence Is Pangram

The Permanent URL is: Teaching Kids Programming – Maximum Number by Inserting Five

Leave a Reply