leetcode 69. Square root of x

implement the  int sqrt(int x) function.

Computes and returns  the square root of x  , where  is a nonnegative integer.

Since the return type is an integer, only the integer part of the result is retained, and the fractional part will be rounded off.

Example 1:

Inputs: 4
 Outputs: 2

Example 2:

Input: 8
 Output: 2
 Explanation: The square root of 8 is 2.82842...,
     Since the return type is an integer, the fractional part will be rounded off.

Solution one:

class Solution {
public:
    int mySqrt(int x) { //Dichotomy
        int low = 0;
        int up = x;
        while(low <= up){
            long mid = (low + up) / 2;
            long s = mid * mid;
            if(x == s) return mid;
            else if(x > s) low = mid + 1;
            else up = mid -1;
        }
        return up;
    }
};

Note that the type of mid and s cannot be int. If int is used, it may cross the bounds and prompt an error exceeding the time limit. The result of multiplying or adding two ints should no longer be represented by int, but instead by long or long long.

Solution two:

class Solution {
public:
    int mySqrt(int x) { //Newton iteration method
    if(x == 0) return 0;      
    double a = 0; // b and a are the results of two adjacent iterations
    double b = 1; // start looking around 1, iteratively approach the target value  
    while(abs(ba) > 0.1) // The judgment condition is abs(ba) > 0.1
    {  
        a = b;  
        b = (b + x/b)/2.0;  
    }  
    return int(b); // The return value is required to be int, and it needs to be cast
    }
};
Using the Newton iteration method, it returns when the difference between the results of the two iterations is not greater than 0.1.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324742292&siteId=291194637