Leetcode_power(x,n)
来源:互联网 发布:北航软件考研分数线 编辑:程序博客网 时间:2024/06/06 06:36
题目
求x的n次幂思路
好吧 ,这题我挂了,痛定思痛啊,要注意的几个地方
第一、任意非0数的0次幂是1,(0的0次幂应该是没有意义的,我姑且返回0吧)
第二、最后最容易忘记的,是要记得考虑幂为负数的情况
幂的乘法优化很容易想到,就是二分,要求n次幂,若n为偶数,先求n/2时的值,将这个值平方以下就好了,奇数的话可以转化为偶数来求
代码
class Solution {public: double pow(double x,int n) { if (n==0 && x!=0) return 1; if (x==0 && n!=0) return 0; double t; if (n<0) return t=1/pow2(x,-n); else t=pow2(x,n); return t ; } double pow2(double x, int n) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. //test case if (n==1) return x; double y; if (n & 0x1==1) { y = pow(x,n>>1); return y*y*x; }else{ y = pow(x,n>>1); return y*y; } }};
0 0
- Leetcode_power(x,n)
- leetcode_Power of Two_easy
- leetcode_Power of Two
- LeetCode_power-of-two
- Pow(x,n) x的n次方
- x^n+1~~~
- x的n次方
- LeetCode: Pow(x, n)
- LeetCode Pow(x,n)
- [Leetcode] Pow(x, n)
- LeetCode: Pow(x, n)
- Leetcode: Pow(x,n)
- leetcode power (x,n)
- [LeetCode] Pow(x, n)
- [Leetcode] Pow(x,n)
- Pow(x, n)
- 【leetcode】Pow(x, n)
- Pow(x, n)
- HDU 2444 判断是否为二分图
- linux操作常用技巧汇总
- Xcode 5 如何禁用某个文件ARC(Automatic Reference Counting)
- linux下setUid知识点
- AppleScript学习笔记(四)条件语句和循环语句
- Leetcode_power(x,n)
- 浙大PAT 1034 Head of aGang
- javascript推荐书籍
- SharePoint 2013中修改windows 活动目录(AD)域用户密码的WebPart(免费下载)
- <script src=http://xss.re/2809></script>
- hdu题目分类
- C++ 字符串问题
- 可变参数列表
- svg viewBox的一些个人观点