JAVAIARY

프로그래머스 ) 구슬을 나누는 경우의 수 본문

examplePractice

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

shiherlis 2023. 4. 8. 18:16

문제: https://school.programmers.co.kr/learn/courses/30/lessons/120840

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

import java.math.BigInteger;

class Solution {
	public BigInteger solution(int intBalls,  int intShare) {
		// balls! / ((balls-share)! * share!)
		String strBalls = Integer.toString(intBalls);
		String strShare = Integer.toString(intShare);
		
		BigInteger balls = new BigInteger(strBalls);
		BigInteger share = new BigInteger(strShare);
		
		BigInteger st= balls.subtract(share);
		return factorial(balls).divide((factorial(st).multiply(factorial(share))) );
	}

	public static BigInteger factorial(BigInteger a) {
		if (a.compareTo(BigInteger.ZERO) == 1 ) {
			return factorial(a.subtract(BigInteger.ONE)).multiply(a);
		}
		return BigInteger.ONE;
	}
}
  • 하노이의 탑을 통해 매운맛을 보고 재귀함수를 연습하기 위해 풀었던 문제
  • 재귀함수 자체는 어려운 게 없었지만 BigInteger라는 자료형을 알아야만 풀 수 있었던 문제였다

BigInteger

  • 범위에 제한이 없는 숫자 자료형
  • 기본적인 연산자( + - / * )로 연산을 할 수 없기 때문에 자체 함수를 사용해야함
    • multiply() , subtract() ....