标签:
Implement int sqrt(int x)
.
Compute and return the square root of x.
example:
sqrt(3) = 1
sqrt(4) = 2
sqrt(5) = 2
1 public int sqrt(int x) { 2 long lo = 0; 3 long hi = x; 4 while (hi >= lo) { 5 long mid = lo + (hi - lo) / 2; 6 System.out.println("befor " + "lo:" + lo + " hi:" + hi + " mid:" + mid); 7 if (x < mid * mid) { 8 hi = mid - 1; // not hi = mid 9 } else { 10 lo = mid + 1; 11 } 12 System.out.println("after " + "lo:" + lo + " hi:" + hi + " mid:" + mid); 13 } 14 return (int)hi; 15 }
标签:
原文地址:http://www.cnblogs.com/luochuanghero/p/4281491.html