实现取平方根的方法
输入int型,返回int型
使用二分法查找,慢慢逼近结果;注意防止溢出,直接用乘法的结果去比较
1 package com.rust.cal;
2
3 public class Sqrtx {
4 /**
5 * 二分法查找
6 * @param x-目标值
7 * @return x的int型平方根
8 */
9 public static int mySqrt(int x) {
10 double diff = 0.000001f;
11 double start = 0;
12 double end = x;
13 double mid;
14 while(end - start > diff){
15 mid = (end + start)/2;
16 if (mid * mid == x) {
17 return (int) mid;
18 }
19 if (mid*mid > x) {
20 end = mid;
21 } else{
22 start = mid;
23 }
24 }
25 return (int) end;
26 }
27 public static void main(String args[]){
28 System.out.println(mySqrt(2147483647));
29 System.out.println(mySqrt(1));
30 System.out.println(mySqrt(0));
31 }
32 }