LeetCode_69---Sqrt(x)

来源:互联网 发布:ubuntu虚拟机分区 编辑:程序博客网 时间:2024/05/17 22:56

Implement int sqrt(int x).

Compute and return the square root of x.

Hide Tags
 Math Binary Search
翻译:求平方值

Code:


/** *  */package From61;/** * @author MohnSnow * @time 2015年7月1日 上午9:51:44 *  */public class LeetCode69 {/** * @param argsmengdx *            -fnst *///268mspublic static int mySqrt(int x) {if (x <= 0) {//注意点一:x是非负的return 0;}int i = 1;long j = x;//注意点二:int的范围太小,适当扩大范围//System.out.println("iaaa: " + i + "j: " + j);long temp = (i + j) / 2;//注意点三:int的范围太小,适当扩大范围while (i < j && i != temp) {if (temp * temp < x) {i = (int) temp;temp = (i + j) / 2;//注意点四:temp的位置} else if (temp * temp > x) {j = (int) temp;temp = (i + j) / 2;//注意点五:temp的位置} else {return (int) temp;}System.out.println("i: " + i + "j: " + j);System.out.println("temp: " + temp);}return (int) temp;}public static void main(String[] args) {int x = 2147395599;x = 2147483647;System.out.println("Math.sqrt: " + Math.sqrt(x));System.out.println("mySqrt: " + mySqrt(x));}}


0 0
原创粉丝点击