자료구조알고리즘/문제풀이
[프로그래머스][Lv.0] 숨어있는 숫자의 덧셈 (2)
포시
2023. 1. 7. 17:58
728x90
문제
https://school.programmers.co.kr/learn/courses/30/lessons/120864
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
내 풀이
def solution(my_string):
if my_string.isdigit(): # (1)
return int(my_string)
answer = []
temp = ''
for str in my_string:
if str.isdigit():
temp += str
else:
answer.append(0 if len(temp) == 0 else int(temp))
temp = ''
answer.append(0 if len(temp) == 0 else int(temp)) # (2)
return sum(answer)
(1): my_string이 자연수로만 이루어졌을 경우
(2): my_string의 마지막이 자연수로 끝날 경우
다른 풀이
def solution(my_string):
s = ''.join(i if i.isdigit() else ' ' for i in my_string)
return sum(int(i) for i in s.split())
숫자가 아닌 경우에 대해 공백으로 처리하고
다시 공백을 기준으로 list로 만든 다음 sum() 처리를 해줬다.
내가 처음 구상한게 이런 방법이었는데 매우 깔끔하게 잘 푼 방법인듯
728x90