[leetcode]Sqrt(x)

Posted on 2013-07-25 19:11  冰天雪域  阅读(156)  评论(0编辑  收藏  举报
class Solution {
public:
    int sqrt(int x) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(x < 1) return 0;
        if(x == 1) return 1;
        
        int start = 1;
        int end = x;
        
        int mid;
        while(start <= end){
            mid = (start + end)/2;
            
            if(x / mid == mid) return mid;
            if(mid < x/mid) start = mid +1;
            else end = mid -1;
            
        }
        
        return (start + end)/2;
    }
};


Copyright © 2024 冰天雪域
Powered by .NET 9.0 on Kubernetes