[Leetcode]Sqrt(x)

来源:互联网 发布:安卓改iphone6在线软件 编辑:程序博客网 时间:2024/04/30 08:36

Sqrt(x)
Total Accepted: 74812 Total Submissions: 310770 Difficulty: Medium

Implement int sqrt(int x).

Compute and return the square root of x.

Subscribe to see which companies asked this question

题目很简单,弄清题意。使用二分查找即可,有一点:输入不一定是个完全平方数,如果不是的话取根的下边界整数。

class Solution {public:    int mySqrt(int x) {        if(x <= 0)  return 0;        int l = 1,r = x;        int mid;        while(l <= r){            mid = l + ((r - l) / 2);            if(mid  > x / mid){                r = mid - 1;            }            else if(mid < x / mid){                l = mid + 1;            }            else{                return mid;            }        }        return r;    }};
0 0
原创粉丝点击