您的位置:首页 > 其它

[leetcode][math] Sqrt(x)

2015-07-01 12:25 281 查看
题目:

Implement
int sqrt(int x)
.

Compute and return the square root of x.
思路一:从1开始逐步逼近 ———可以accept但是效率很低
class Solution {
public:
int mySqrt(int x) {
if (x < 0) return -1;
if (x <= 1) return x;
long long res = 2;
long pre = 1;
while (res*res <= x){
pre = res;
res = res * res;
}
res = pre;
while (res*res <= x){
pre = res;
res = 2 * res;
}
res = pre;
while (res*res <= x){
++res;
}
return res - 1;
}
};
思路二:二分查找——8ms

注意判断条件是mid和x/mid的关系

class Solution {
public:
int mySqrt(int x) {
if(x<=1)  return x;
int left = 1;
int right = x;
while(left<=right)  {
//   int mid = left + ((right-left)>>1);
int mid = (right+left)>>1;
if(mid == x/mid)  return mid;
else if(mid < x/mid)  left = mid + 1;
else  right = mid - 1;
}
return right;
}
};


思路三:牛顿迭代法——8ms

class Solution {
public:
int mySqrt(int x) {
if (x ==0)  return 0;
double pre;
double cur = 1;
do {
pre = cur;
cur = x / (2 * pre) + pre / 2.0;
} while (abs(cur - pre) > 0.00001);
return int(cur);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: