LeetCode69 Sqrt(x)
题意:
Implement int sqrt(int x)
.
Compute and return the square root of x.(Medium)
分析:
二分搜索套路题,不能开方开尽的时候,取结果整数位。
注意:判定条件中,用x / mid == mid而不是 mid * mid == x,否则可能出现int溢出。
代码:
1 class Solution { 2 public: 3 int mySqrt(int x) { 4 if (x == 0) { 5 return 0; 6 } 7 int start = 0, end = x; 8 while (start + 1 < end) { 9 int mid = start + (end - start) / 2; 10 if (x / mid == mid) { 11 return mid; 12 } 13 else if (x / mid > mid) { 14 start = mid; 15 } 16 else { 17 end = mid; 18 } 19 } 20 if (x / end == end) { 21 return end; 22 } 23 return start; 24 } 25 };