※ 백준 (Baekjoon)/[Java] 문제 풀이 ( Solve the problems)
[실버 4] 1676. 팩토리얼 0의 개수 (Java)
J 크
2023. 8. 6. 23:22
728x90
반응형
https://www.acmicpc.net/problem/1676
1676번: 팩토리얼 0의 개수
N!에서 뒤에서부터 처음 0이 아닌 숫자가 나올 때까지 0의 개수를 구하는 프로그램을 작성하시오.
www.acmicpc.net
BigInteger..?
※ 문제를 요약하면 아래와 같습니다.
▶ N! (팩토리얼) 의 결과 값에서 뒤에서 부터 처음 0이아닌 숫자가 나올 때까지 0의 갯수 구하기
(ex - 23200150000 = 4개 )
▶ 입력은 N
▶ 출력은 0의 갯수
◈ Input - 1
10
◈ Output - 1
2
◈ Input - 2
4
◈ Output - 2 ( 3 or 5로 구성할 수 없음 )
-1
◎ 코드 작성 전, 아래와 같이 솔루션을 정리하였습니다.
▶ 팩토리얼을 구하는 과정에서, 뒤에 0이 나올 때마다 카운트 하고 10으로 나눔
▶ 팩토리얼 계산 종료 후 마지막으로 뒤에서 부터 0을 탐색
▶ 500! 까지 표현하기 위해 자료형 BigInteger 사용
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class Main{
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(bf.readLine());
BigInteger Factorial = new BigInteger("1");
BigInteger Remainder;
int nCount = 0;
for(int i = 1; i <= N; i++) {
Factorial = Factorial.multiply(BigInteger.valueOf(i));
Remainder = Factorial.remainder(BigInteger.valueOf(10));
if(Remainder.compareTo(BigInteger.valueOf(0)) == 0) {
Factorial = Factorial.divide(BigInteger.valueOf(10));
nCount++;
}
}
while(Factorial.remainder(BigInteger.valueOf(10)).compareTo(BigInteger.valueOf(0)) == 0) {
nCount++;
Factorial = Factorial.divide(BigInteger.valueOf(10));
}
System.out.println(nCount);
}
}
자료형을 생각 못하다가 BigInteger라는 java의 표현 방식을 찾아서.. 해결을 완료하였습니다.
읽어주셔서 감사합니다!
Good Luck! (피드백 고맙습니다)