문제
N!에서 뒤에서부터 처음 0이 아닌 숫자가 나올 때까지 0의 개수를 구하는 프로그램을 작성하시오.
입력
첫째 줄에 N이 주어진다. (0 ≤ N ≤ 500)
출력
첫째 줄에 구한 0의 개수를 출력한다.
코드
import java.awt.*;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
BigInteger result = factorial(BigInteger.valueOf(N));
String s_result = String.valueOf(result);
int count = 0;
for (int i = s_result.length() - 1; i >= 0; i--) {
if (s_result.charAt(i) == '0') {
count++;
} else {
break;
}
}
System.out.println(count);
}
static BigInteger factorial(BigInteger n) {
if (n.compareTo(BigInteger.ONE) <= 0) {
return BigInteger.ONE;
}
return n.multiply(factorial(n.subtract(BigInteger.ONE)));
}
}
문제 보자마자 팩토리얼 값 구해서 뒤에서부터 확인하면 되겠다는 생각으로 코드를 짰는데 int형으로 구현하면 틀린다.
int의 범위를 넘어간다는 말을 보고 BigInteger로 바꿨는데 수정하면서도 이건 아닌 것 같다는 생각을 했다.
다른 사람들은 어떻게 풀었는지 보다가 색다른 방법을 알아냈다.
소인수분해를 했을 때 2*5의 개수만큼 0이 생긴다는 것이고, 소인수분해를 했을 때 2의 개수가 5의 개수보다 많아서 결국 5의 개수만큼 0이 생긴다.
이 규칙을 찾아내면 factorial 함수를 만들 필요도, BigInteger를 사용할 필요도 없어진다.

import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
int count = 0;
while (N >= 5) {
count += N / 5;
N /= 5;
}
System.out.println(count);
}
}
아직 코테 공부가 부족하다는 생각을 많이 하게 되는 문제였다..
문제 출처
'Study > Test(Java)' 카테고리의 다른 글
| [백준] 11651 좌표 정렬하기 2 Java (1) | 2024.04.27 |
|---|---|
| [백준] 7568 덩치 Java (0) | 2024.04.26 |
| [백준] 1436 영화감독 숌 Java (1) | 2024.04.26 |
| [백준] 10989 수 정렬하기 3 Java (0) | 2024.04.26 |
| [백준] 2869 달팽이는 올라가고 싶다 (1) | 2024.04.26 |