leetcode 50 Pow(x, n)
2016-08-12 09:03
441 查看
Implement pow(x, n).
以上就是这道题目的题干,看起来非常简单没有什么过多的要求,实际上也是用最简单的方法做的,但是这道题目需要注意的细节很多,解法如下:
最简单的方法可以利用math库函数进行计算
class Solution {
public:
double myPow(double x, int n)
{
return pow(x,n);
}
};
但是,我们也可以自己来写一下这个函数,毕竟给出的函数名是myPow,所以写法是这样的
class Solution {
public:
double myPow(double x, int n)
{
if(x==1||n==0)
{
return 1;
}
if(x==-1)
{
if(n%2==0)
{
return 1;
}
return -1;
}
double result=1;
if(n>0)
{
for(int i=0;i<n;i++)
{
result=x*result;
if(abs(result)<0.00001)
break;
}
}
else
{
for(int i=0;i>n;i--)
{
result=result/x;
if(abs(result)<0.00001)
{
break;
}
}
}
return result;
}
};
其中需要注意的几个细节包括:
1、n的正负零取值,这影响着计算方式;
2、对于x的判断,x=1、-1时不需要进行过多的计算,否则会时间超出;
3、对计算结果的精度判定,在计算过程中需要对小于精度的计算结果进行跳出。
以上就是这道题目的题干,看起来非常简单没有什么过多的要求,实际上也是用最简单的方法做的,但是这道题目需要注意的细节很多,解法如下:
最简单的方法可以利用math库函数进行计算
class Solution {
public:
double myPow(double x, int n)
{
return pow(x,n);
}
};
但是,我们也可以自己来写一下这个函数,毕竟给出的函数名是myPow,所以写法是这样的
class Solution {
public:
double myPow(double x, int n)
{
if(x==1||n==0)
{
return 1;
}
if(x==-1)
{
if(n%2==0)
{
return 1;
}
return -1;
}
double result=1;
if(n>0)
{
for(int i=0;i<n;i++)
{
result=x*result;
if(abs(result)<0.00001)
break;
}
}
else
{
for(int i=0;i>n;i--)
{
result=result/x;
if(abs(result)<0.00001)
{
break;
}
}
}
return result;
}
};
其中需要注意的几个细节包括:
1、n的正负零取值,这影响着计算方式;
2、对于x的判断,x=1、-1时不需要进行过多的计算,否则会时间超出;
3、对计算结果的精度判定,在计算过程中需要对小于精度的计算结果进行跳出。
相关文章推荐
- 【LeetCode】LeetCode50 Pow(x, n)
- leetcode50_Pow(x, n)
- Leetcode(50):Pow(x, n)
- [LeetCode]50 Pow(x, n)
- [LeetCode-50] Pow(x, n)(数值的整数次方)
- leetcode || 50、Pow(x, n)
- LeetCode(50) Pow(x, n)
- 50. Pow(x, n) LeetCode
- LeetCode---(50)Pow(x, n)
- leetcode 50 : Pow(x, n)
- Leetcode 50 Pow(x, n)
- Leetcode 50 Pow(x, n) 两种方式求解
- [leetcode 50] Pow(x, n)
- LeetCode 50 - Pow(x, n)
- leetcode-50-Pow(x, n)
- LeetCode50 Pow(x, n) 解题报告
- LeetCode 50:Pow(x, n)
- LeetCode(50) Pow(x,n)
- [LeetCode 50] Pow(x, n)
- LeetCode 50: Pow(x, n)