Search This Blog

Friday, December 7, 2012

LeetCode: Sqrt(x)


Sqrt(x)
Implement int sqrt(int x).
Compute and return the square root of x.
public class Solution {
    public int sqrt(int x) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(x<0) return -1;
        if(x==0) return 0;
        
        double y = ((double)x)/2.;
        while(Math.abs(y*y-x)>0.00001){
            y=(y+x/y)/2.;
        }
        return (int) y;
    }
}

3 comments:

Unknown said...
This comment has been removed by the author.
Anonymous said...

Your Leetcode solutions always top Google results. However, lacking briefest comments leaves your code useless for others...

Anonymous said...

I always learn from your codes and you code is very clean and heuristic enough to dig into it. Forget the impolite comments above.