sqrt(X)

Yohan Kim·2021년 8월 30일
0

problem

제곱근의 정수 부분만 리턴하는 코드입니다.
1 -> 1
2 -> 1
3 -> 1
4 -> 2
25 -> 5
37 -> 6
https://leetcode.com/problems/sqrtx

solution

class Solution {
public:
    int mySqrt(int x) {
        if(x == 0) return 0;
        if(x > 2147395600) return 46340;
        int sqr = 1, i = 1; 
        while(sqr < x)
        {
            sqr = sqr + 2*i +1;
            if(sqr > x)
            {
                break;
            }
            i++;
        }
        return i;
    }
};

예외처리를 한 후, a^2과 (a+1)^2 의 제곱의 차이를 이용하여 전 항의 제곱수를 이용하여 다음 제곱수를 예측하고 리턴하는 방식입니다.

profile
안녕하세요 반가워요!

0개의 댓글