求X的平方根

求X的平方根

package com.mtons.mblog.leetcode;

/**
 * 求X的平方根
 *
 */
class Solution {

    /**
     * 二分法
     * @param x
     * @return
     */
    public int mySqrt(int x) {
        //返回結果只要整數,小於1的平方根都是0.多,捨棄後爲0
        if (x==0 || x==1)
        {
            return x;
        }
        int left=1;
        int high=x;
        int mid=0;
        while (left<=high)
        {
            mid=left+((high-left)>>1);
            //這裏不要用平方積,當mid過大會越界,所以用除更好
            if (mid==x/mid)
            {
                return mid;
            }else if (mid<x/mid)
            {
                left=mid+1;
            }else {
                high=mid-1;
            }
        }
        return high;
    }

    /**
     * 數學公式
     * @param x
     * @return
     */
    public int mySqrt1(int x) {
        if (x < 2)
            return x;
        int curr = (int) Math.exp(0.5 * Math.log(x)) + 1;//注意判斷條件應該是取值+1的平方和x對比
        return (long) curr * curr > x ? curr - 1 : curr;//curr的平方爲方便特殊取值應該用long
    }

    /**
     * 牛頓迭代
     * https://b23.tv/av42180634/p1
     * @param x
     * @return
     */
    public int mySqrt2(int x) {
        long n = x;
        while (n * n > x) {
            n = (n + x / n) / 2;
        }
        return (int) n;
    }

    public static void main(String[] args) {
        // default impl. delegates to StrictMath
        // Note that hardware sqrt instructions
        // frequently can be directly used by JITs
        // and should be much faster than doing
        // Math.sqrt in software.
        //public static native double sqrt(double a);
        Math.sqrt(2);
        Solution solution = new Solution();
        System.out.println(solution.mySqrt2(16));
    }
}

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