처음부터 차근차근

class2 - 1676번 팩토리얼 0의 개수 (자바) 본문

알고리즘

class2 - 1676번 팩토리얼 0의 개수 (자바)

_soyoung 2024. 5. 21. 11:09
반응형

문제 : https://www.acmicpc.net/problem/1676

 

문제의 최댓값인 500!은 자릿수만 1135자 가까이 돼서 일반적인 int문으로 데이터를 담는것이 불가능하다.

그래서 BigInteger을 써야한다.

 

 

문제에서 사용되는 개념

BigInteger

타입 범위 기본형/참조형 저장 위치
int -2,147,483,648 ~ 2,147,483,647 기본형(value type) Stack
BigInteger 무한 (Infinity) 참조형(reference type) Heap

 

선언 방법

import java.math.BigInteger;
BigInteger num = new BigInteger("1");

 

 

연산

num.subtract(BigInteger.valueOf(2))
num.multiply(BigInteger.valueOf(2))
num.divide(BigInteger.valueOf(2))
num.remainder(BigInteger.valueOf(2))

 

 

형변환

BigInteger.valueOf(1); // int -> BigIntger
num.intValue(); //BigIntger -> int
num.longValue(); //BigIntger -> long
num.floatValue(); //BigIntger -> float
num.doubleValue(); //BigIntger -> double
num.toString(); //BigIntger -> String

 

 

풀이

import java.util.*;
import java.io.*;
import java.math.BigInteger;

public class Main
{
	public static void main(String[] args) {
		try {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

            // 팩토리얼 구하기
            int num = Integer.parseInt(br.readLine());
            BigInteger fac = new BigInteger("1");
            for (int i = num; i > 0; i--) {
                fac = fac.multiply(BigInteger.valueOf(i));
            }
            
            char[] arr = String.valueOf(fac).toCharArray();
            
            int count = 0;    
            
            for (int i = arr.length - 1; i >= 0; i--) {
                if (arr[i] == '0') {
                    count++;
                }
                else {
                    break;
                }
            }
            
            bw.write(String.valueOf(count));
            
            br.close();
            bw.flush();
            bw.close();
		}
		catch (IOException e) {
          System.out.println("IOException 발생");
		}
	}
}

처음에 int로 담았다가 틀려서 BigInteger 사용해서 다시 짰다.

 

반응형
Comments