Implement int sqrt(int x)
.
Compute and return the square root of x.
好的解法: 二分法,注意边界条件。当不满足循环条件时,low>high,经过验证,low-1为正确答案。时间:16ms
1 class Solution { 2 public: 3 int mySqrt(int x) { 4 if(x == 0) return 0; 5 if(x == 1) return 1; 6 7 int low = 0, high = x; 8 int mid = (low + high) / 2; 9 10 while(low <= high){ 11 if(x / mid == mid) return mid; 12 else if(x / mid < mid) high = mid - 1; 13 else low = mid + 1; 14 15 mid = (low + high) / 2; 16 } 17 return low - 1; 18 19 } 20 };
自己写的:调用系统函数。面试肯定过不了啊。。时间:14ms。是怎么实现的呢??
1 class Solution { 2 public: 3 int mySqrt(int x) { 4 return floor(sqrt(x*1.00)); 5 } 6 };