LeetCode 题解(173): Pow(x, n)
来源:互联网 发布:数据结构与算法的关系 编辑:程序博客网 时间:2024/06/06 16:45
题目:
Implement pow(x, n).
题解:
要用二分法递归。还要区分n的正负。
C++版:
class Solution {public: double myPow(double x, int n) { if(n == 0) return 1; if(n == 1) return x; double temp = myPow(x, abs(n / 2)); if(n > 0) { if(n & 1) return temp * temp * x; else return temp * temp; } else { if(n & 1) return 1 / (temp * temp * x); else return 1 / (temp * temp); } }};
Java版:
public class Solution { public double myPow(double x, int n) { if(n == 0) return 1; if(n == 1) return x; double temp = myPow(x, Math.abs(n / 2)); if(n > 0) { if((n & 1) == 0) return temp * temp; else return temp * temp * x; } else { if((n & 1) == 0) return 1 / (temp * temp); else return 1 / (temp * temp * x); } }}
Python版:
class Solution: # @param {float} x # @param {integer} n # @return {float} def myPow(self, x, n): if n == 0: return 1.0 if n == 1: return x if n > 1: return self.pow(x, n) else: return 1.0 / self.pow(x, -n) def pow(self, x, n): if n == 0: return 1.0 if n == 1: return x temp = self.pow(x, n / 2) if n % 2 == 0: return temp * temp else: return temp * temp * x
0 0
- LeetCode 题解(173): Pow(x, n)
- LeetCode题解:Pow(x,n)
- Leetcode题解:Pow(x, n)
- LeetCode Algorithms 50. 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
- startActivityForResult与startActivity
- 华为OJ(尼科彻斯定理)
- Lucas定理(C(n,m)mod p)
- Python初学教程
- Android-使用ListView把SQLite中的数据显示至屏幕
- LeetCode 题解(173): Pow(x, n)
- 异常
- iOS面试题1
- asp.net网站图表制作
- PAT 1035. Password (20)
- Android Alarm自上而下 调试浅析
- JAVAWEB电影售票
- java基础--正则表达式
- hdu 5386 Cover (逆向暴力模拟)