leetcode笔记:Pow(x, n)
来源:互联网 发布:复杂网络中的幂律分布 编辑:程序博客网 时间:2024/05/01 01:12
一. 题目描述
Implement pow(x, n).
二. 题目分析
实现pow(x, n),即求x
的n
次幂。
最容易想到的方法就是用递归直接求n
个x
的乘积,这里需要根据n
的值,判断结果是正数还是负数,这种方法的时间复杂度为O(n)
。
更加快捷的方法是,使用分治法,对于x^n,有一下公式:
x^n = x^(n / 2) * x^(n / 2) * x^(n % 2)
使用这种方法的时间复杂度为O(logn)
。
三. 示例代码
#include <iostream>using namespace std;class Solution {public: double pow(double x, int n) { if (n == 0) return 1; if (n > 0) return power(x, n); else return 1 / power(x, -1 * n); }private: double power(double x, int n) { if (n == 0) return 1; double a = power(x, n / 2); // 递归求x^(n/2) if (n % 2 == 0) return a * a; else return a * a * x; }};
四. 小结
此题为分治思路的经典题型之一。
5 0
- leetcode笔记:Pow(x, n)
- LeetCode: Pow(x, n)
- LeetCode Pow(x,n)
- [Leetcode] Pow(x, n)
- LeetCode: Pow(x, n)
- Leetcode: Pow(x,n)
- [LeetCode] Pow(x, n)
- [Leetcode] Pow(x,n)
- 【leetcode】Pow(x, n)
- [LeetCode]Pow(x, n)
- [leetcode]Pow(x, n)
- LeetCode-Pow(x, n)
- LeetCode - Pow(x, n)
- LeetCode | Pow(x, n)
- Pow(x, n) -leetcode
- 【leetcode】Pow(x, n)
- 【Leetcode】Pow(x, n)
- LeetCode Pow(x, n)
- Quartz的cron表达式
- 评教系统优化之使用事务批量导入DataTable
- hibernate--关系映射归纳和总结
- 项目进度计划
- ListView 适配器实现getviewtypecount() 数组越界IndexOutOfBoundException
- leetcode笔记:Pow(x, n)
- maven打tar.gz zip包—maven-assembly-plugin
- [知其然不知其所以然-15] cgroup概述
- MyBatis项目-shop购物系统
- Oracle高级查询,GROUP BY
- Xcode7中 http请求报错App Transport Security has blocked a cleartext HTTP
- 虚拟机中使用linux系启用文件共享之后的文件存在的位置
- 2015年年尾总结
- Oracle表分区