It seems that coding tests are conducted overseas in interviews with engineers, and in many cases, the main thing is to implement specific functions and classes according to the theme.
As a countermeasure, it seems that a site called Let Code will take measures.
A site that trains algorithmic power that can withstand coding tests that are often done in the home.
I think it's better to have the algorithm power of a human being, so I'll solve the problem irregularly and write down the method I thought at that time as a memo.
Leet Code Table of Contents Starting from Zero
Last time Leet Code Day48 starting from zero "26. Remove Duplicates from Sorted Array"
Right now, I'm prioritizing the Medium of the Top 100 Liked Questions. I solved all Easy, so if you are interested, please go to the table of contents.
Twitter I'm doing it.
The difficulty level is Easy. There are more Goods, and I thought it was an interesting problem, so I will introduce it.
Given a positive integer, num
, consisting of only 6 and 9.
The problem is that you can change the number from 6 to 9 or 9 to 6 by only one digit, so design an algorithm that returns num
as the maximum value that can be changed.
Input: num = 9669 Output: 9969 Explanation: Changing the first digit results in 6669. Changing the second digit results in 9969. Changing the third digit results in 9699. Changing the fourth digit results in 9666. The maximum number is 9969.
Input: num = 9996 Output: 9999 Explanation: Changing the last digit 6 to 9 results in the maximum number.
Input: num = 9999 Output: 9999 Explanation: It is better not to apply any change.
You can see that if you change the number of digits from 6 to 9, you will get a larger number.
So I thought about using the replace function.
In the replace function, the argument is (target to be replaced, element to be replaced, number of times between maximum values), so if you check the element of the string from the front and return the one replaced only once, it will actually work. I thought, and wrote as follows.
class Solution:
def maximum69Number (self, num: int) -> int:
return int(str(num).replace('6','9',1))
# Runtime: 28 ms, faster than 73.29% of Python3 online submissions for Maximum 69 Number.
# Memory Usage: 13.8 MB, less than 58.88% of Python3 online submissions for Maximum 69 Number.
It's pretty good. In addition, since the replace function receives only a character string, it must be converted to a character string once, then applied to the replace function, and then set to int when returning.
Thank you for your hard work this time.
Recommended Posts