Sqrt(x)

看cast type比较重要,

public class Solution {
    public int sqrt(int x) {
        // 巧妙使用二分法
        // ref http://www.cnblogs.com/springfor/p/3857772.html
        
        int low =0, high=x;
        while(low<=high){
            long mid = (long) low+(high-low)/2;
            if(mid*mid==x) return (int) mid;
            if(mid*mid<x){
                low = (int) mid+1;
            }else high = (int) mid-1;
        }
        return high;
    }
}

 

posted @ 2015-06-03 02:07  世界到处都是小星星  阅读(140)  评论(0编辑  收藏  举报