翻译:求平方值
Code:
/**
*
*/
package From61;
/**
* @author MohnSnow
* @time 2015年7月1日 上午9:51:44
*
*/
public class LeetCode69 {
/**
* @param argsmengdx
* -fnst
*/
//268ms
public 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));
}
}