LeetCode之Sqrt(x)

来源:互联网 发布:java和捷安特哪个好 编辑:程序博客网 时间:2024/05/17 01:46

Implement int sqrt(int x).

Compute and return the square root of x.


注意:越界问题

class Solution {public:    int sqrt(int x) {        if(x<0) return -1;        if(x==0||x==1)  return x;        int start,end;        long long mid;              //!!!!!!int may cause overflow        start=1,end=x>>1;        while(end>=start){            mid=(start+end)>>1;            if(mid*mid<=x && (mid+1)*(mid+1)>x)                return mid;            else if(mid*mid>x)                end=mid-1;            else                start=mid+1;         }//while    }};


0 0
原创粉丝点击