leetcode 50 Pow(x, n)
来源:互联网 发布:mac os ipconfig 编辑:程序博客网 时间:2024/06/14 16:06
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、对计算结果的精度判定,在计算过程中需要对小于精度的计算结果进行跳出。
- 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)
- [leetcode] #50 Pow(x,n)
- LeetCode-50 Pow(x, n)
- Pow(x, n) - LeetCode 50
- 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)
- leetcode 50:Pow(x, n)
- 【NOI2001T1】食物链-并查集
- Face Alignment at 3000 FPS via Regressing Local Binary Features(CVPR2014)读后感(first pass)
- 数据结构与算法(2)顺序表
- 华为oj--走格子
- HDU 5584 青蛙跳跳跳 小小的数论题
- leetcode 50 Pow(x, n)
- EL表达式遍历存了数组的集合
- 【win32】day09-对话框/子控件/静态块/按钮/文本编辑框
- CentOS纯命令基础——网络的连接与防火墙的禁用
- 在线文档预览方案-office web apps
- Windows平台下sbt的安装设置
- 暴力_______Rikka with Parenthesis II( hdu 5831 2016多校第八场)
- 加入博客家庭,第一个博客(并没有实质内容:-D)
- C++学习005-循环