您的位置:首页 > 其它

Leetcode_sqrtx

2014-03-30 15:42 387 查看
地址:http://oj.leetcode.com/problems/sqrtx/

Implement
int sqrt(int x)
.

Compute and return the square root of x.
思路:主要是处理2147483647这个case吧。同时也要注意上溢出的问题,不然也会TLE。

两个参考代码,一个152ms,一个96ms

//152ms
class Solution {
public:
int sqrt(int x) {
if(x<=1)
return x;
int i = 2;
for(; i*i<=x &&i*i>0; ++i)
{
if((i+100)*(i+100)>0 &&(i+100)*(i+100)<x)
{
i+=100;
}
}
return i-1;
}
};

//96ms
class Solution {
public:
int sqrt(int x) {
if(x<=1)
return x;
int i = 2;
for(; i*i<=x &&i*i>0; ++i)
{
if((i+1000)*(i+1000)>0 &&(i+1000)*(i+1000)<x)
{
i+=1000;
}
}
return i-1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: