일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Notice
Recent Posts
Recent Comments
Link
Tags
- 최빈값 구하기 자바
- 모스부호(1) 자바
- 자바 팩토리얼
- string과 stringbuilder 성능 최적화
- 티스토리챌린지
- 펙토리얼
- 유클리드 호제법이란?
- 소인수분해 구하는 공식
- stringbuilder란
- string과 stringbuilder 성능 차이
- 프로그래머스 공 던지기 게임
- string과 stringbuilder
- 프로그래머스 최반값 구하기 자바
- 외계행성의 나이 자바
- 경우의 수 자바
- string과 stringbuilder의 차이
- 오블완
- 자바 합성수 찾기
- 개미 군단 자바
- 피자 나눠먹기(2) 자바
- 피자 나눠먹기(2)
- 프로그래머스
- 프로그래머스 문자열 정렬하기(1)
- 자바 소인수분해
- 배열 순환 문제 공식
- 프로그래머스 피자 나눠먹기(3)
- 숨어있는 숫자의 덧셈 (1) 자바
- string과 stringbuilder의 차이점
- 배열 순환
- 배열 순환 자바
Archives
- Today
- Total
여름 언덕에서 배운 것
[0단계/6점] 구슬을 나누는 경우의 수 본문
n개의 구슬중 m개를 뽑는 경우의 수를 구하라 !
공식은 다음과 같다.
관건은 팩토리얼을 어떻게 구현할 것인가 !
class Solution {
public int solution(int balls, int share) {
return combination(balls,share);
}
private int combination(int balls, int share) {
int answer = factorial(balls)/(factorial(share)*factorial(balls-share));
return answer;
}
private int factorial(int num) {
int result =1;
for(int i=1; i<=num; i++){
result*=i;
}
return result;
}
}
여기서 문제는 정수 오버플로우ㄱ ㅏ발생했는지 제출하니까 틀린문제가 많았다.
int의 최대값은 2,147,483,647인데, 30!은 훨씬 큰 값이라 long 또는 BigInteger를 써야 함
✅ 개선 코드 (BigInteger 사용)
import java.math.BigInteger;
class Solution {
public BigInteger solution(int balls, int share) {
return combination(balls, share);
}
private BigInteger combination(int balls, int share) {
return factorial(balls).divide(factorial(share).multiply(factorial(balls - share)));
}
private BigInteger factorial(int num) {
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= num; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
}
BigInteger result = BigInteger.ONE; 이게 뭐야? 🤔
이 코드는 BigInteger 타입의 변수 result를 1로 초기화하는 코드
728x90
'가랑비에 옷 젖는 줄 모른다 💻 > 🌰코테문풀_꾸준히' 카테고리의 다른 글
[0단계/1점]합성수 찾기 (0) | 2025.03.13 |
---|---|
공 던지기 ,원형 큐에서 다음 위치 찾기, 보드 게임(말판 이동)에서 N칸씩 이동 공통점 (1) | 2025.03.07 |
[0단계/1점]가위 바위 보 (0) | 2025.03.05 |
[0단계/1점]모스부호(1) (1) | 2025.03.05 |
[0단계/1점]순서쌍의 개수 (0) | 2025.03.05 |