Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chèn số 5 để tạo số lớn nhất trong Python


Cho số n, tìm số lớn nhất có thể tạo bằng cách chèn chữ số 5 vào bất kỳ vị trí nào trong n.

Ví dụ, n = 826, đầu ra 8526.

Các bước giải quyết:

  • temp := str(n).
  • ans := -inf.
  • Với i từ 0 đến độ dài temp:
    • cand = temp[:i] + '5' + temp[i:].
    • Nếu i == 0 và temp[0] == '-', bỏ qua vòng lặp này.
    • ans = max(ans, int(cand)).
  • Trả về ans.

Ví dụ minh họa

class Solution:
    def solve(self, n):
        temp = str(n)
        ans = float('-inf')
        for i in range(len(temp) + 1):
            cand = temp[:i] + '5' + temp[i:]
            if i == 0 and temp[0] == '-':
                continue
            ans = max(ans, int(cand))
        return ans

ob = Solution()
print(ob.solve(826))

Đầu vào

826

Đầu ra

8526