[백준] 1334번 다음 팰린드롬 수

거북이·2023년 2월 12일
0

백준[골드5]

목록 보기
5/82
post-thumbnail

💡문제접근

  • 정답률이 20%인 이유가 있었다. 일반적인 방법으로 돌리면 시간초과(TLE)가 발생한다.

  • 이 문제는 각각의 경우를 나눠서 생각해야한다.

    • ①. 만약 9 or 99 or 999 ... 이런 형태의 경우라면?
    • ②. 만약 입력받은 값이 1 ~ 8의 경우라면?
    • ③. 만약 입력받은 값의 길이가 홀수라면?
    • ④. 만약 입력받은 값의 길이가 짝수라면?

💡코드(메모리 : 31256KB, 시간 : 44ms)

import sys
input = sys.stdin.readline

N = input().strip()
len_N = len(N)
half_N = N[:(len_N + 1) // 2]

# 9 or 99 or 999 or 9999 ... 이런 경우라면?
if N == "9" * len_N:
    print(int(N) + 2)
elif len_N == 1:
    print(int(N) + 1)
# 만약 숫자의 길이가 홀수인 경우
elif len_N % 2 != 0:
    temp = half_N + half_N[-2::-1]
    if int(temp) > int(N):
        print(temp)
    else:
        temp = str(int(half_N) + 1)
        temp = temp[:] + temp[-2::-1]
        print(temp)
# 만약 숫자의 길이가 짝수인 경우
else:
    temp = half_N + half_N[::-1]
    if int(temp) > int(N):
        print(temp)
    else:
        temp = str(int(half_N) + 1)
        temp = temp[:] + temp[::-1]
        print(temp)

💡소요시간 : 1h 10m

0개의 댓글