티스토리 뷰
기존에 작성한 코드
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int[] n = new int[t];
for (int i = 0; i < t; i++) {
n[i] = sc.nextInt();
}
String[] a = new String[t];
for (int i = 0; i < n.length; i++) {
a[i] = Integer.toString(pac(n[i])).replaceAll("0+$", "");
//a[i] = a[i].replaceAll("0+$", "");
}
for (int i = 0; i < a.length; i++) {
System.out.println(a[i].charAt(a[i].length()-1));
}
}
static int pac(int n) {
if(n < 2) {
return n;
}
return n*pac(n-1);
}
}
결과는 런타임 에러..
이것저것 시도해보다 보니 int형보다 큰 숫자가 들어가서 그렇다고 한다.
새로 작성한 코드
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int[] n = new int[t];
for (int i = 0; i < t; i++) {
n[i] = sc.nextInt();
}
String[] a = new String[t];
for (int i = 0; i < n.length; i++) {
a[i] = pac(n[i]).toString();
a[i] = a[i].replaceAll("0+$", "");
}
for (int i = 0; i < a.length; i++) {
System.out.println(a[i].charAt(a[i].length()-1));
}
}
static BigInteger pac(int n) {
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
}
빅인티저 BigInteger는 처음 이번 계기로 처음 알게되었다.
int와 long은 크기 제한이 있는 기본형 타입이며, BigInteger는 그 범위에 제한이 없고 매우 큰 정수를 처리할 수 있다는 장점이 있다.
Type | 최소값 | 최대값 |
int | -2,147,483,648 (-2^31) | 2,147,483,647 (2^31 - 1) |
long | -9,223,372,036,854,775,808 (-2^63) | 9,223,372,036,854,775,807 (2^63 - 1) |
BigInteger | 시스템 메모리에 의존 (이론상 무제한) | 시스템 메모리에 의존 (이론상 무제한) |
'코테' 카테고리의 다른 글
[백준 1157] 단어 공부 JAVA - LinkedHashSet, HashMap 사용 (2) | 2024.11.09 |
---|---|
[백준 1316] 그룹 단어 체커 JAVA - 데크(Deque) 사용 (0) | 2024.11.08 |
[백준 11718] 그대로 출력하기 JAVA (0) | 2024.10.30 |
[백준 10809] 알파벳 찾기 JAVA (0) | 2024.10.29 |
[백준 2588] 곱셈, [2908] 상수 JAVA (0) | 2024.01.29 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- dockerspring
- 트리
- 백준알고리즘
- 웹스퀘어
- Spring
- 알고리즘
- docker배포
- 백준자바
- controller
- docker컨테이너
- tomcat
- 백준
- BigDecimal
- websquare
- SpringBoot
- docker
- MySQL
- 클라우드
- Java
- 노드
- db
- 자바
- 톰캣
- 티스토리챌린지
- 그리드
- google cloud run
- 오블완
- Apache
- docker앱배포
- 이클립스
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
글 보관함