Skip to content

[Algorithm] 자릿수 더하기 #63

Description

@hwangJi-dev

💬 문제

[코딩테스트 연습 - 자릿수 더하기](https://school.programmers.co.kr/learn/courses/30/lessons/12931)


💬 Idea

n이 0이 될 때까지 while문을 돌며 answer에 n을 10으로 나눈 나머지를 더하고, n은 10으로 나눈 몫으로 바꿔준다.


💬 풀이

func solution(_ n:Int)->Int{varanswer:Int=0varn= n
while n !=0{
answer += n %10
n /=10}return answer
}

💬 더 나은 방법?

func solution(_ n:Int)->Int{returnString(n).reduce(0,{ $0 + Int(String($1))! })}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions