Skip to content

Latest commit

 

History

History

69

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Given a non-negative integer x, compute and return the square root of x.

Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.

Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.

 

Example 1:

Input: x = 4
Output: 2

Example 2:

Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.

 

Constraints:

  • 0 <= x <= 231 - 1

Companies:
LinkedIn, Amazon, Google, Microsoft, Apple, Uber, tiktok

Related Topics:
Math, Binary Search

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/sqrtx/
// Author: github.com/lzl124631x
// Time: O(sqrt(N))
// Space: O(1)
class Solution {
public:
    int mySqrt(int x) {
        long i = 0;
        while (i * i <= x) ++i;
        return i - 1;
    }
};

Solution 2. Binary Search

L <= R template.

// OJ: https://leetcode.com/problems/sqrtx/
// Author: github.com/lzl124631x
// Time: O(logN)
// Space: O(1)
class Solution {
public:
    int mySqrt(int x) {
        long L = 0, R = x;
        while (L <= R) {
            long M = (L + R) / 2;
            if (M * M <= x) L = M + 1;
            else R = M - 1;
        }
        return R;
    }
};

Or use L < R template

// OJ: https://leetcode.com/problems/sqrtx/
// Author: github.com/lzl124631x
// Time: O(logN)
// Space: O(1)
class Solution {
public:
    int mySqrt(int x) {
        long L = 0, R = x;
        while (L < R) {
            long M = (L + R + 1) / 2;
            if (M * M <= x) L = M;
            else R = M - 1;
        }
        return L;
    }
};

Solution 3. Newton's method

Reference: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division

// OJ: https://leetcode.com/problems/sqrtx/
// Author: github.com/lzl124631x
// Time: O(logN)
// Space: O(1)
class Solution {
public:
    int mySqrt(int x) {
        long r = x;
        while (r * r > x) r = (r + x / r) / 2;
        return r;
    }
};