Skip to content

Latest commit

 

History

History
181 lines (149 loc) · 3.25 KB

File metadata and controls

181 lines (149 loc) · 3.25 KB

English Version

题目描述

实现 int sqrt(int x) 函数。

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

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

示例 1:

输入: 4
输出: 2

示例 2:

输入: 8
输出: 2
说明: 根号 8 是 2.82842..., 
     由于返回类型是整数,小数部分将被舍去。

解法

Python3

class Solution:
    def mySqrt(self, x: int) -> int:
        if x == 0:
            return 0
        left, right = 1, x
        while left < right:
            mid = (left + right + 1) >> 1
            # mid*mid <= x
            if x // mid >= mid:
                left = mid
            else:
                right = mid - 1
        return left

Java

class Solution {
    public int mySqrt(int x) {
        if (x == 0) {
            return 0;
        }
        int left = 1, right = x;
        while (left < right) {
            int mid = (left + right + 1) >>> 1;
            if (x / mid >= mid) {
                // mid*mid <= x
                left = mid;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }
}

C++

class Solution {
public:
    int mySqrt(int x) {
        if (x == 0) {
            return 0;
        }
        int left = 1, right = x;
        while (left < right) {
            int mid = left + ((right - left + 1) >> 1);
            if (x / mid >= mid) {
                left = mid;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }
};

JavaScript

/**
 * @param {number} x
 * @return {number}
 */
var mySqrt = function(x) {
    if (x == 0) {
        return 0;
    }
    let left = 1;
    let right = x;
    while (left < right) {
        const mid = (left + right + 1) >>> 1;
        if (x / mid >= mid) {
            left = mid;
        } else {
            right = mid - 1;
        }
    }
    return left;
};

Go

func mySqrt(x int) int {
	if x == 0 {
		return 0
	}
	left, right := 1, x
	for left < right {
		mid := left + (right-left+1)>>1
		if x/mid >= mid {
			left = mid
		} else {
			right = mid - 1
		}
	}
	return left
}

C#

public class Solution {
    public int MySqrt(int x) {
        if (x == 0) {
            return 0;
        }
        int left = 1, right = x;
        while (left < right)
        {
            int mid = left + right + 1 >> 1;
            if (x / mid >= mid)
            {
                left = mid;
            } 
            else 
            {
                right = mid - 1;
            }
        }
        return left;
    }
}

...