69. Sqrt(x)
Implement int sqrt(int x)
.
Compute and return the square root of x.
x is guaranteed to be a non-negative integer.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8 Output: 2 Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.
实现sqrt
C++:
1 class Solution { 2 public: 3 int mySqrt(int x) { 4 if (x <= 1){ 5 return x ; 6 } 7 int left = 1 ; 8 int right = x ; 9 while(left <= right){ 10 int mid = left + (right - left) / 2 ; 11 int sqrt = x / mid ; 12 if (mid == sqrt){ 13 return mid ; 14 }else if (mid > sqrt){ 15 right = mid - 1 ; 16 }else{ 17 left = mid + 1 ; 18 } 19 } 20 return min(left,right) ; 21 } 22 };
C++(37ms):
1 class Solution { 2 public: 3 int mySqrt(int x) { 4 long r = x ; 5 while(r*r > x){ 6 r = (r + x/r) /2 ; 7 } 8 return r ; 9 } 10 };