Dazzling 개발 노트

[백준] 2417 - 정수 제곱근 (Java) 본문

Algorithm/백준

[백준] 2417 - 정수 제곱근 (Java)

dj._.dazzling 2023. 8. 11. 23:08

[백준] 2417 - 정수 제곱근 (Java)

문제

https://github.com/allrightDJ0108/CodingTestStudy/commit/26429316cf03dd26ace86644eec2a95eb941a0d7

풀이/후기

BigInteger를 자료형으로 이용해야 한다

long을 이용하여 풀면 틀렸습니다 처리가 된다..ㅎ

0부터 N까지 start, end시점 잡아서

mid보다 큰지 작은지를 따져서 답을 구해주면 된다.

코드

package BinarySearch;

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

public class Problem2417 {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		String num = br.readLine();
		BigInteger N = new BigInteger(num);

		BigInteger start = BigInteger.ZERO;
		BigInteger end = N;
		BigInteger min = BigInteger.ZERO;
		
		while (start.compareTo(end) == -1 || start.compareTo(end) == 0) {
			BigInteger sum = start.add(end);
			BigInteger mid = sum.divide(BigInteger.TWO);
			BigInteger result = mid.pow(2);
			
			if (N.compareTo(result) == -1 || N.compareTo(result) == 0) {
				min = mid;
				end = mid.subtract(BigInteger.ONE);
			} else {
				start = mid.add(BigInteger.ONE);
			}
		}
		
		System.out.println(min);
	}
}

Commit

https://github.com/allrightDJ0108/CodingTestStudy/commit/26429316cf03dd26ace86644eec2a95eb941a0d7

참고