[프로그래머스] LV.0 자릿수 더하기 / 파이썬(Python)

디딧·2022년 11월 23일

프로그래머스

목록 보기
35/36
post-thumbnail

문제 설명

정수 n이 매개변수로 주어질 때 n의 각 자리 숫자의 합을 return하도록 solution 함수를 완성해주세요

제한사항

0 ≤ n ≤ 1,000,000

idea

n을 문자열로 바꾼 후 하나씩 추출해서 더한다.

풀이 1

def solution(n):
    str_n = str(n)
    answer = 0
    for i in str_n:
        answer += int(i)
    return answer

풀이 2

def solution(n):
    return sum([int(i) for i in str(n)])

풀이 2가 풀이 1보다 속도가 느렸다.
굳이 리스트로 만들 필요는 없었다.

다른사람 풀이

def solution(n):
    return sum(list(map(int, str(n))))
profile
M.S. in Statistics, 2022 - present

0개의 댓글