[LeetCode] 69. Sqrt(x)
Posted C·Moriarty
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 69. Sqrt(x)相关的知识,希望对你有一定的参考价值。
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)的主要内容,如果未能解决你的问题,请参考以下文章