题目:
Implement int sqrt(int x)
.
Compute and return the square root of x.
链接: http://leetcode.com/problems/sqrtx/
2/14/2017, Java,不是自己想的。。。
二分法,需要进行第3行的判断。最后返回hi的原因是从while loop挑出来的时候lo是比hi大的,实际上我们应该选小的那个值,就是hi
1 public class Solution { 2 public int mySqrt(int x) { 3 if (x <= 1) return x; 4 5 int lo = 0, hi = x; 6 int mid; 7 8 while( lo <= hi) { 9 mid = lo + (hi - lo) / 2; 10 if (mid < x / mid) { 11 lo = mid + 1; 12 } else if (mid > x / mid) { 13 hi = mid - 1; 14 } else { 15 return mid; 16 } 17 } 18 return hi; 19 } 20 }
牛顿法,肯定也不是自己想的。
还是注意input = 1的情况
1 public class Solution { 2 public int mySqrt(int x) { 3 if (x <= 1) return x; 4 5 double lastY = x / 2; 6 double Y = (lastY + x / lastY) / 2; 7 8 while (Y != lastY) { 9 lastY = Y; 10 Y = (lastY + x / lastY) / 2; 11 } 12 return (int)Y; 13 } 14 }
4/27/2017
算法班,套用公式,不过不如一刷第一种方法好。
1 class Solution { 2 /** 3 * @param x: An integer 4 * @return: The sqrt of x 5 */ 6 public int sqrt(int x) { 7 // write your code here 8 if (x <= 0) return 0; 9 if (x == 1) return 1; 10 11 int start = 1, end = x; 12 while (start + 1 < end) { 13 int mid = start + (end - start) / 2; 14 if (x / mid == mid) { 15 return mid; 16 } else if (x / mid > mid) { 17 start = mid; 18 } else { 19 end = mid; 20 } 21 } 22 if (x / start >= start) { 23 return start; 24 } else { 25 return end; 26 } 27 } 28 }