Monday, November 25, 2013

LeetCode Problem : Sqrt(x)

Problem


Implement int sqrt(int x).
Compute and return the square root of x.

Code

int sqrt(int x) {
    // IMPORTANT: Please reset any member data you declared, as
    // the same Solution instance will be reused for each test case.
    if(x  < 2)
        return x;
    double n = x;
    while(1){
        double num = x/n;
        if(n - num < 0.0000001 && n - num > -0.0000001)
            return static_cast<int>(max(n,num));
        n = (n + num)/2.0;
    }
}

No comments:

Post a Comment