새소식

Test/Coding Tests

[Programmers] 구슬을 나누는 경우의 수

  • -

func solution(_ balls:Int, _ share:Int) -> Int {
    
    if (balls == share){
        return 1
    }
    
    let result = factorial(balls) / factorial(balls - share) / factorial(share)
    return Int(NSDecimalNumber(decimal: result))
}

func factorial(_ n: Int) -> Decimal{
    var num: Decimal = Decimal(1)
    for i in 1...n {
        num *= Decimal(i)
    }
    return num
}

Int 형으로 처음에 풀다가 Demical로 변형하여 풀었더니 성공하였다.

 

Int 형 팩토리얼(재귀함수)

func factorial(_ n: Int) -> Int{
    
    if n == 0 || n == 1{
        return 1
    }
    
    return n * factorial(n-1)
}

 

출처

 

[프로그래머스][Swift] 구슬을 나누는 경우의 수

문제: 구슬을 나누는 경우의 수 프로그래머스 코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭

dokit.tistory.com

728x90

'Test > Coding Tests' 카테고리의 다른 글

[Programmers] 공 던지기  (2) 2023.10.28
[Programmers] 2차원으로 만들기  (0) 2023.10.25
[Programmers] 외계행성의 나이  (0) 2023.10.22
[Programmers] 배열 뒤집기  (0) 2023.10.14
[Programmers] 최빈값 구하기  (0) 2023.10.08
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.