算法分析:利用折半查找,降低算法复杂度。前面求x得y次幂,也是将y/2,都是为了降低复杂度。
//折半查找的思想 public class Sqrt { public int sqrt(int x) { int low = 0; int high = x; while(low <= high) { long mid = (low + high)/2; if(mid*mid > x)//为了防止mid*mid溢出,将mid定义为long { high = (int)mid - 1; } else if(mid*mid < x) { low = (int)mid + 1; } else { return (int)mid; } } return high; } }