ITeye博客

[leetcode] sqrt(x)

standalone · 2013-04-15 07:44 · algorithm · 编程语言 · Markdown

I have talked about this question in my previous posts.

http://leetcode.com/onlinejudge#question_69 Q: Implement int sqrt(int x).

Compute and return the square root of x.

Solution:


public class Solution {
    public int sqrt(int x) {
        // Start typing your Java solution below
        // DO NOT write main() function
        double error = 0.0000001f;
        double high = x;
        double low = 0;
        while(high-low> error){
            double mid = (high+low)/2;
            if(mid*mid>x){
                high = mid;
            }else {
                low = mid;
            }
        }
        return (int)Math.floor(high);
    }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。