【Leetcode】69.Sqrt(x)

Question:

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

Example 1:

Input: 4
Output: 2

Example 2:

Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.

 Tips:重写sqrt()函数,使其返回一个int类型的平方跟。

package easy;

/*
 * Implement int sqrt(int x).

Compute and return the square root of x.
 */
public class L69 {
	public int mySqrt(int x) {
//直接调用Math.sqrt,将返回值硬转型为int
		return (int) StrictMath.sqrt(x);
	}

	public int mySqrt2(int x) {
//二分的方式,找到x的平方跟。
		if (x == 0)
			return 0;
		int low = 1;
		int high = x;
		while (low <= high) {
			int mid = low + (high - low) / 2;
			if (mid == x / mid) {
				return mid;
			} else if (mid > x / mid) {
				high = mid - 1;
			} else {
				low = mid + 1;
			}
		}
		return high;
	}

	public static void main(String[] args) {
		L69 l69 = new L69();
		int x = 4;
		int count = l69.mySqrt(2147395599);
		System.out.println(count);
	}
}

 

调用Math.sqrt()函数

public class L69 {
     public int mySqrt(int x) {
            int ans=(int) Math.sqrt(x);
            System.out.println(ans);
            return ans;
        }
     public static void main(String[] args) {
        L69 l69 = new L69();
        int x=4;
        l69.mySqrt(0);
    }
}

注:

①Math.sqrt() 参数为double类型

public static double sqrt(double a) {
        return StrictMath.sqrt(a); // 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.
    }

②StrictMath.sqrt (文档中说 使用StrictMath.sqrt比使用Math.sqrt更快)

 /**
     * Returns the correctly rounded positive square root of a
     * {@code double} value.
     * Special cases:
     * <ul><li>If the argument is NaN or less than zero, then the result
     * is NaN.
     * <li>If the argument is positive infinity, then the result is positive
     * infinity.
     * <li>If the argument is positive zero or negative zero, then the
     * result is the same as the argument.</ul>
     * Otherwise, the result is the {@code double} value closest to
     * the true mathematical square root of the argument value.
     *
     * @param   a   a value.
     * @return  the positive square root of {@code a}.
     */
    public static native double sqrt(double a);

 ③事实证明 Math比StrictMath更快:

  Math----------2ms

 public int mySqrt(int x) {
        return (int) Math.sqrt(x);
    }
StrictMath---------4ms
 public int mySqrt(int x) {
        return (int)StrictMath.sqrt(x);
    }

 

 
posted @ 2017-07-04 09:49  于淼  阅读(264)  评论(0编辑  收藏  举报