전공/알고리즘 + 코테
[JAVA] 백준 #1271 - 엄청난 부자2
BBungyaLog
2024. 1. 15. 14:40
문제

입력

출력


풀이
- 첫번째 풀이
단순하게 접근하여 Int형으로 정수를 입력받아 나눗셈과 나머지를 사용하였다.
// 1271
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
sc.close();
System.out.println(n/m);
System.out.println(n%m);
}
}
이 코드는 더 큰 정수를 처리할 수 없어 런타임 에러가 발생하였다.
- 두번째 풀이
더 큰 정수를 처리하기 위해 BigInteger형으로 정수를 입력받았다.
BigInteger n = sc.nextBigInteger();
BigInteger m = sc.nextBigInteger();
이렇게 설정하게 되면 /나 %연산자를 사용할 수 없기 때문에 divide() 메소드와 remainder()메소드를 사용했다.
// 1271
import java.util.Scanner;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BigInteger n = sc.nextBigInteger();
BigInteger m = sc.nextBigInteger();
sc.close();
System.out.println(n.divide(m));
System.out.println(n.remainder(m));
}
}