1 Sqrt(x)
Implement int sqrt(int x).Compute and return the square root of x.
因为这里都是整数,可以直接采用二分法求解
int mySqrt(int x) {
if (x <= 1) return x;
int begin = 1, end =x, mid = 0;
while (begin<=end)
{
mid = (begin + end) / 2;
if (mid<x / mid) //不要用乘法判断,否则会越界
{
begin = mid + 1;
}
else if (mid>x / mid)
{
end = mid - 1;
}
else if (mid == x / mid)
return mid;
}
return end;
}
牛顿迭代法:设r是
当第
这里记
int mySqrt(int x) {
if (x == 0)
return 0;
double last;
double res = 1;
do
{
last = res;
res = x / (2 * last) + last / 2.0;
} while (abs(res - last) > 0.001);
return int(res);
}
2 Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
用一个vector容器保存目录,当有多个’/’出现时去掉重复的,当出现’..’时是返回上一个目录,如果容器大小不为0,要去掉容器末尾的元素。
string simplifyPath(string path) {
vector<string> res;
int len=path.length();
string mid;
int start=0;
while(start<len)
{
while(path[start]==‘/‘&&start<len)
start++; //去掉重复‘/‘
while(path[start]!=‘/‘&&start<len)
{
//记录下每一级目录
mid+=path[start];
start++;
}
if(mid=="."||mid=="")
{
mid.clear(); //进入下一次循环前,记得清空mid
continue;
}
if(mid=="..")
{
if(res.size()>0)
res.pop_back();
mid.clear();
continue;
}
res.push_back(mid);
mid.clear();
}
string result;
int n=res.size();
for(int i=0;i<n;i++)
{
result=result+"/"+res[i];
}
if(result=="") result="/";
return result;
}
原文地址:http://blog.csdn.net/zhulong890816/article/details/45950751