1323. Maximum 69 Number
Description
You are 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).
Example 1:
- 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.
Example 2:
- Input: num = 9996
- Output: 9999
- Explanation: Changing the last digit 6 to 9 results in the maximum number.
Example 3:
- Input: num = 9999
- Output: 9999
- Explanation: It is better not to apply any change.
Constraints:
- 1 <= num <= 104
numconsists of only6and9digits.
💡 Hint 1:
Convert the number in an array of its digits.
💡 Hint 2:
Brute force on every digit to get the maximum number.
Submitted Code
class Solution:
def maximum69Number (self, num: int) -> int:
s = list(str(num))
for i in range(len(s)):
if s[i] == '6':
s[i] = '9'
break
return int(''.join(s))
Runtime: 0 ms | Beats 100.00%
Memory: 19.45 MB | Beats 9.70%
가장 왼쪽의 6만 9로 바꾸면 되기 때문에 6을 찾는 순간 바로 반복문을 종료하면 된다.
Other Solutions
1st
class Solution:
def maximum69Number(self, num):
return int(str(num).replace('6', '9', 1))
time complexity: 𝑂(𝑛)
space complexity: 𝑂(𝑛)
2nd
class Solution:
def maximum69Number (self, num: int) -> int:
i = 0
tem = num
sixidx = -1
while tem > 0:
if tem % 10 == 6:
sixidx = i #refresh sixidx when found 6 at large digit.
tem = tem//10
i += 1
return (num + 3 *(10**sixidx)) if sixidx != -1 else num
문자열 변환 없이 수학적으로 풀 수 있다.