백준/Java

[백준 자바] 22193번(Multiply) | BigInteger 클래스 사용하기

gamzaggang7 2024. 3. 5. 15:06
728x90

난이도 - 브론즈 5

문제

Write a program that computes a product of two non-negative integers A and B. The integers are represented in decimal notation and have N and M digits, respectively.

입력

The first line contains the lengths N and M, separated by a space. A is given on the second and B on the third line. The numbers will not have leading zeros.

출력

Output the product of A and B without leading zeros.

제한

  • 1 ≤ N, M ≤ 50 000

서브태스크

번호배점제한
1 20 N, M ≤ 4
2 20 N, M ≤ 9
3 30 N, M ≤ 5 000
4 30 No additional constraints

 


728x90

 

문제를 잘 읽어보면 N과 M을 곱하는게 아니라, N자리 수와 M자리 수를 곱하는 문제다.

N과 M의 최대 자릿수가 50,000인데 long의 범위가 - 9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807니까 입력값이 20 1 이 들어와도 벌써 long의 범위를 넘는 것이다. 이런 경우에는 BigInteger를 쓴다.

자세한 설명은 따로 포스팅함 -> https://gamzaggang7.tistory.com/86

 

[Java] BigInteger 클래스란? - 엄청 큰 정수 다루기

BigInteger 클래스 BigInteger 클래스는 long의 범위를 넘는 엄청 큰 정수를 다루며, java.math 패키지에 포함되어 있다. 메서드를 통해 사칙연산 등을 할 수 있으며, 사칙연산의 대상또한 BigInteger이어야

gamzaggang7.tistory.com

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

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

        br.readLine();
        BigInteger a = new BigInteger(br.readLine());
        BigInteger b = new BigInteger(br.readLine());

        bw.write(String.valueOf(a.multiply(b)));

        bw.flush();
        br.close();
        bw.close();
    }
}

 

입력 첫번째 줄은 필요없으니까 따로 변수에 저장 안해도 된다.

곱할때는 a*b 이렇게 하는게 아니라 BigInteger의 Multiply(BigInteger) 메서드를 사용해야 한다. 곱하는 인자도 BigInteger이어야 한다.

 

 

 

 

728x90