11.2 Sqrt(x)

来源:互联网 发布:it公司招人难 编辑:程序博客网 时间:2024/06/05 02:15

Approach I: Binary Search. 

The sqrt(x) can be not larger than x/2+1. //why?

Time: O(logn), Space: O(1)

public class Solution {    public int sqrt(int x) {        if(x < 2) return x;//what if x <0?        int l = 1;        int r = x/2 + 1;        while(l <= r){            int m = (l+r)/2;            if(x/m>=m && x/(m+1)<m+1){//x is between [m^2, (m+1)^2)                return m;            }            else if(x/m < m){//x < m^2                r = m-1;            }            else{//x > (m+1)^2                l = m+1;            }                    }        return 0;    }}

Approach II: Newton Method

//why res = 1?

public class Solution {    //Newton method    public int sqrt(int x) {        if(x == 0) return 0;        double last = 0;        double res = 1;//why?        while(res != last){           last = res;           res = (res + x/res)/2;       }       return (int) res;    }}



0 0