The Solution to LeetCode 69 Sqrt(x)

来源:互联网 发布:钱咖淘宝返利 编辑:程序博客网 时间:2024/05/20 03:37
Question:

Implement int sqrt(int x).

Compute and return the square root of x.

思路:本题采用二分法进行求解。

Answer:

class Solution {public:    int mySqrt(int x) {        int low=0;        int high=x;        int mid=0;        if(x<=1)          {              return x;          }          while(low+1<high)          {            mid = low + (high-low)/2;          if(mid > x/mid)          {              high = mid;          }          else if(mid < x/mid)          {              low = mid;          }          else          {              return mid;          }        }      return low;    }};

Run code results:

Your input
17
Your answer
4
Expected answer
4

0 0