본문 바로가기
코딩테스트/프로그래머스 Lv.0

[코테/0레벨] ★ 구슬을 나누는 경우의 수

by moca7 2025. 1. 22.

 

 

 

 

 

ㅁ 최초 풀이

 

class Solution {
    public int solution(int balls, int share) {
        
        int child = 1;
        
        for(int i = 1; i <= balls; i++){
            child *= i;
        }
        
        
        int parent = 1;
        
        int nMinusM = balls - share;
        for(int i = 1; i <= nMinusM; i++){
            parent *= i;
        }
        
        for(int i = 1; i <= share; i++){
            parent *= i;
        }
        
        return child/parent;
        
    }
}

 

 

- int형이어서 팩토리얼의 계산 결과가 큰 수면 제대로 계산되지 않음.

- long형도 한계가 있어서 BigInteger를 사용했다. 

 

 

 

 

 

ㅁ 최종 풀이

 

 

import java.math.BigInteger;

class Solution {
    public BigInteger solution(int balls, int share) {
        
        BigInteger child = new BigInteger("1");
        
        for(int i = 1; i <= balls; i++){
            child = child.multiply(BigInteger.valueOf(i));
        }
        
        
        BigInteger parent = new BigInteger("1");
        
        int nMinusM = balls - share;
        for(int i = 1; i <= nMinusM; i++){
            parent = parent.multiply(BigInteger.valueOf(i));
        }
        
        for(int i = 1; i <= share; i++){
            parent = parent.multiply(BigInteger.valueOf(i));
        }
        
        return child.divide(parent); 
        
    }
}

 

 

- import java.math.BigInteger; 

- BigInteger를 초기화하기 위해서는 문자열을 인자 값으로 넘겨주어야 한다. BigInteger가 문자열로 되어 있기 때문.

 

 

 

BigInteger bigNumber1 = new BigInteger("100000");
BigInteger bigNumber2 = new BigInteger("10000");
		
System.out.println("덧셈(+) :" +bigNumber1.add(bigNumber2));
System.out.println("뺄셈(-) :" +bigNumber1.subtract(bigNumber2));
System.out.println("곱셈(*) :" +bigNumber1.multiply(bigNumber2));
System.out.println("나눗셈(/) :" +bigNumber1.divide(bigNumber2));
System.out.println("나머지(%) :" +bigNumber1.remainder(bigNumber2));

 

- BigInteger은 문자열이기에 사칙연산이 안됩니다.

그렇기에 BigIntger 내부의 숫자를 계산하기 위해서는 BigIntger 클래스 내부에 있는 메서드를 사용해야 합니다.

 

 

 

 

ㅁ BigInteger 형변환

 

BigInteger bigNumber = BigInteger.valueOf(100000); //int -> BigIntger

int int_bigNum = bigNumber.intValue(); //BigIntger -> int
long long_bigNum = bigNumber.longValue(); //BigIntger -> long
float float_bigNum = bigNumber.floatValue(); //BigIntger -> float
double double_bigNum = bigNumber.doubleValue(); //BigIntger -> double
String String_bigNum = bigNumber.toString(); //BigIntger -> String

 

 

'코딩테스트 > 프로그래머스 Lv.0' 카테고리의 다른 글

[코테/0레벨] 특별한 이차원 배열 1  (0) 2025.01.22
[코테/0레벨] ad 제거하기  (0) 2025.01.22
피자 나눠 먹기 (3)  (0) 2025.01.19
배열의 유사도  (0) 2025.01.19
삼각형의 완성조건 (1)  (0) 2025.01.19