【睡前水題】之X的平方根

在這裏插入圖片描述

  • 方法一:公式法(瞭解即可,面試別寫,不能調用庫函數)
    在這裏插入圖片描述
  • 方法二:
    二分查找
class Solution {
    public int mySqrt(int x) {
       int l=0,r=x,res=0;
       while(l<=r){
           int mid= l+(r-l)/2;
           if((long)mid*mid<=x){
               res= mid;
               l=mid+1;
            }else{
               r=mid-1;
           }
       }
       return res;
    }
}
  • 方法三
    牛頓迭代
class Solution {
    public int mySqrt(int x) {
        if (x == 0) {
            return 0;
        }

        double C = x, x0 = x;
        while (true) {
            double xi = 0.5 * (x0 + C / x0);
            if (Math.abs(x0 - xi) < 1e-7) {
                break;
            }
            x0 = xi;
        }
        return (int)x0;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章