Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

69. Sqrt(x) #150

Open
Tcdian opened this issue May 9, 2020 · 1 comment
Open

69. Sqrt(x) #150

Tcdian opened this issue May 9, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented May 9, 2020

69. Sqrt(x)

实现 int sqrt(int x) 函数。

计算并返回 x 的平方根,其中 x 是非负整数。

由于返回类型是整数,结果只保留整数的部分,小数部分将被舍去。

Example 1

Input: 4
Output: 2

Example 2

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.
@Tcdian
Copy link
Owner Author

Tcdian commented May 9, 2020

Solution

  • JavaScript Solution
/**
 * @param {number} x
 * @return {number}
 */
var mySqrt = function(x) {
    let result;
    let left = 0;
    let right = x;
    while (left <= right) {
        const mid = Math.floor((left + right) / 2);
        if (mid * mid === x) {
            result = mid;
            break;
        } else if (mid * mid < x) {
            result = mid;
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return result;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant