본문 바로가기
프로그래머스/[프로그래머스 - JAVA] Lv.0

[프로그래머스 - JAVA] 구술을 나누는 경우의 수

by 코딩하는 흰둥이 2023. 3. 14.
반응형

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

 

프로그래머스

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

programmers.co.kr

아이고 길다...

 

  • 다른 사람 풀이
import java.math.BigInteger;
class Solution {
    public int solution(int balls, int share) {
        int answer = 0;
          BigInteger bN[] = new BigInteger[balls+1];

                bN[0]= new BigInteger("1");
                for(int i=1;i<=balls;i++) {

                    bN[i] = new BigInteger(Integer.toString(i));
                    bN[i] = bN[i].multiply(bN[i-1]);
                }

                answer=bN[balls].divide(bN[share].multiply(bN[balls-share])).intValue();
        
        return answer;
    }
}

몇시간 동안 생각해봤는데 도무지 답을 찾지 못하였다

다른 분의 풀이를 보니 BigInteger 를 사용하여 풀이하셨는데 코드길이가 짧지만 간단하지가 않다...

 

우선 BigInteger가 무슨 동작을 하는지 부터 알아봐야겠다 들어만 봤지 사용해본적 없는 클래스이다.

 

 

  • BigInteger Class

int 와 long 타입을 넘어서는 "무한대" 의 값을 가지는 타입이 바로 BigInteger 라고 한다.

BigInteger는 int 와 long 타입과는 달리 문자열 형태로 되어 있어 초기화 할때에도 숫자가 아닌 문자열로 선언하게 된다.

import 시에는 java.math.BigInteger 로 math 안에 포함되어있다.

 

 

  • BigInteger 예제
        // 문자열로 변수선언 및 초기화시킨다.
        BigInteger test1 = new BigInteger("100");
        BigInteger test2 = new BigInteger("20");

        // 사칙연산은 메서드를 이용해야한다.
        System.err.println(" + :"+test1.add(test2));
        System.err.println(" - :"+test1.subtract(test2));
        System.err.println(" * :"+test1.multiply(test2));
        System.err.println(" / :"+test1.divide(test2));
        System.err.println(" % :"+test1.remainder(test2));

 

  • BigInteger 형 변환
        // int -> BigInteger 로 변형
        BigInteger test1 = BigInteger.valueOf(1000); 
                
        // BigInteger -> int로 변형
        int int_test = test1.intValue();

        // BigInteger -> long으로 변형
        long long_test = test1.longValue();

        // BigInteger -> float로 변형
        float float_test = test1.floatValue();

        // BigInteger -> double로 변형
        double double_test = test1.doubleValue();

        // BigInteger -> String으로 변형
        String string_test = test1.toString();

 

 

다른 분이 사용한 메서드를 이해할 정도만 우선 정리해 보았다

댓글