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.
(1)暴力搜索
1 class Solution { 2 public: 3 int mySqrt(int x) { 4 if(x<=0) 5 return x; 6 int begin=1; 7 int end=x; 8 int mid=0; 9 while(begin<=end) 10 { 11 mid=(begin+end)/2; 12 if(mid==x/mid) 13 return mid; 14 else if(mid<x/mid) 15 begin=mid+1; 16 else 17 end=mid-1; 18 } 19 return end; 20 } 21 };
(2)牛顿迭代
1 class Solution { 2 public: 3 int mySqrt(int x) 4 { 5 long long v=x; 6 while(v*v>x) 7 v=(v+x/v)>>1; 8 return v; 9 } 10 };