LeetCode Pow(x, n)
来源:互联网 发布:net域名为什么不值钱 编辑:程序博客网 时间:2024/05/16 10:25
原题链接在这里:https://leetcode.com/problems/powx-n/
这道题和Sqrt(x)以及Divide Two Integers都是原有公式的题。这类题目一般用二分法(Sqrt(x))和以2为基地accumulation表示法(Divide Two Integers)都是为了节省时间到O(logn).
这里采用了二分法,建立一个helper返回n为正数时的power, 主函数里分开调用即可。
helper中采用递归,原理就是x^n = x^(n/2) *x^(n/2) * (n == 奇数)*x, 终止条件是n==0时返回一.
AC Java:
public class Solution { public double myPow(double x, int n) { if(n<0){ return 1/helper(x,-n); }else{ return helper(x,n); } } private double helper(double x, int n){ if(n == 0){ return 1.0; } double half = helper(x,n/2); if(n%2 == 0){ return half * half; }else{ return half * half * x; } }}
0 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)
- Pow(x, n) -leetcode
- 【leetcode】Pow(x, n)
- 【Leetcode】Pow(x, n)
- LeetCode Pow(x, n)
- Leetcode: Pow(x, n)
- ZigZag Conversion
- Leetcode: Longest Palindromic Substring
- javascript DOM编程艺术笔记——CH3 DOM
- 面向对象(继承+抛出异常)-第20天
- javascript DOM编程艺术笔记——CH5 Best practise
- LeetCode Pow(x, n)
- javascript DOM编程艺术笔记——CH7 creating markup on the fly
- Python安装PIL遇到‘Could not find a version that satisfies the requirement PIL’
- 渐进增强和平稳退化
- HTML 、XHTML和 HTML5辨析
- python 数据结构编程技巧
- 利用Session防止表单重复提交
- 笔试题之:快排求第n大的数字
- 2015长春网络赛(HDU5437,5438,5439,5441,5442,5443,5444,5446)