C solution, Newton's method, no float/double, no function call (e.g abs(), sqrt(), pow()), no multiply, 4ms


  • 1
    J
    int mySqrt(int x) {
        int p1, p2, n;
        
        if (x < 2) {
            return x;
        }
        n = x >> 1; // Maybe a good guess
        for (p1 = 0, p2 = 0; n != p1 && n != p2; )  {
            p2 = p1;
            p1 = n;
            n = (n + x / n) >> 1;
        }
        return n < p1 ? n : p1;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.