1. 程式人生 > >[LeetCode] 69. Sqrt(x)

[LeetCode] 69. Sqrt(x)

n-n max put pre 利用 col ima HERE int

Implement int sqrt(int x).

Compute and return the square root of x, where x is guaranteed to be a non-negative integer.

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

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.


題意:開方
這裏肯定是不使用Math庫的前提下,
我們可以利用二分的思想去開方,開方反過來就是平方,Integer.MAX_VALUE 開方是46340,也就是最大的解,因為存在越界的情況
這個數字需要我們提前算出來。之後只要二分去找,mid*mid <= target , (mid+1)*(mid+1) > target 就行了
class Solution {
    public int mySqrt(int x) {
        int l = 0;
        int r = 46340;
        if (r*r < x)
            
return r; if (x == 1 || x == 0) return x; while (r - l > 5) { int mid = (l + r) / 2; if (mid * mid < x) { l = mid; } else if (mid * mid > x) { r = mid; }
else return mid; } for (int i = l; i <= r; i++) { if (i*i == x) return i; if (i*i < x && (i+1)*(i+1) > x) return i; } return 0; } }

[LeetCode] 69. Sqrt(x)