boj - 11720: 숫자의 합 (python)

minions·2022년 2월 1일
0

풀이1

N = int(input())
number = input()
sum = 0

for i in number:
  sum += int(i)

print(sum)

결과

  • time complexity : o(n) - number가 길 수록 linear search 길이가 길어진다. 모든 수를 다 더해야 하므로 n번 반복이 불가피하다.
  • space complexity : o(1) - input을 제외하고 사용한 변수가 상수 sum 뿐이다.
  • 메모리/시간/코드길이 : 30864KB, 76ms, 87B

접근 전환

라이브러리를 사용하여 time complexity를 o(1)으로 줄여보고자 하였다.

풀이2

from functools import reduce

N = int(input())
number = list(input())

print(reduce(lambda x,y:int(x)+int(y), number))

결과

답은 맞지만, 결국 lambda가 input을 순회하므로 space complexity는 o(n)이다.

  • time complexity : o(1)
  • space complexity : o(n)

메모리, 시간, 가독성 관점에서 품질이 나빠졌다. 여러 메소드를 사용하기 때문인 것으로 보인다.

  • 메모리/시간/코드길이 : 32344KB, 100ms, 118B

0개의 댓글