174.Sqrt(x)
题目:
Implement int sqrt(int x)
.
实现int sqrt(int x)。
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
计算并返回x的平方根,其中x保证为非负整数。
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.
说明:8的平方根为2.82842 ...,并且由于小数部分被截断,因此返回2。
解答:
方法一:二分搜索
1 class Solution { 2 public int mySqrt(int x) { 3 if(x<=1) return x; 4 int left=0,right=x; 5 while(left<right){ 6 int mid=left+(right-left)/2; 7 if(x/mid>=mid) //mid*mid<=x 8 left=mid+1; 9 else 10 right=mid; 11 } 12 return right-1; 13 } 14 }
方法二:牛顿迭代
1 class Solution { 2 public int mySqrt(int x) { 3 long res=x; 4 while(res*res>x) 5 res=(res+x/res)/2; 6 return (int) res; 7 } 8 }
详解:
方法二详解:
要求x2 = n,令f(x)=x2-n,则xi+1=(xi + n/xi) / 2