LeetCode 50 — Pow(x, n)(C++ Java Python)
2014-03-21 11:04
399 查看
题目:http://oj.leetcode.com/problems/powx-n/
Implement pow(x, n).
题目翻译:
实现pow(x,n)。
分析:
二分。
C++实现:
Java实现:
Python实现:
感谢阅读,欢迎评论!
Implement pow(x, n).
题目翻译:
实现pow(x,n)。
分析:
二分。
C++实现:
class Solution { public: double pow(double x, int n) { if(n < 0) { return 1.0 / power(x, -n); } else { return power(x, n); } } double power(double x, int n) { if(n == 0) { return 1; } double tmp = pow(x, n / 2); if(n & 0x01) { return tmp * tmp * x; } else { return tmp * tmp; } } };
Java实现:
public class Solution { public double pow(double x, int n) { if (n < 0) { return 1.0 / power(x, -n); } else { return power(x, n); } } public double power(double x, long n) { if (n == 0) { return 1; } double tmp = power(x, n / 2); if ((n & 0x01) == 1) { return tmp * tmp * x; } else { return tmp * tmp; } } }
Python实现:
class Solution: # @param x, a float # @param n, a integer # @return a float def pow(self, x, n): if n < 0: return 1.0 / self.power(x, -n) else: return self.power(x, n) def power(self, x, n): if n == 0: return 1 tmp = self.power(x, n / 2) if n & 0x01 == 1: return tmp * tmp * x else: return tmp * tmp
感谢阅读,欢迎评论!
相关文章推荐
- LeetCode 14 — Longest Common Prefix(C++ Java Python)
- LeetCode 144 — Binary Tree Preorder Traversal(C++ Java Python)
- [LeetCode] 013. Roman to Integer (Easy) (C++/Java/Python)
- LeetCode 73 — Set Matrix Zeroes(C++ Java Python)
- [LeetCode] 020. Valid Parentheses (Easy) (C++/Java/Python)
- LeetCode 1 — Two Sum(C++ Java Python)
- Leetcode_powx-n(c++ and python version)
- LeetCode 2 — Add Two Numbers(C++ Java Python)
- [LeetCode] 015. 3Sum (Medium) (C++/Java/Python)
- LeetCode 98 — Validate Binary Search Tree(C++ Java Python)
- LeetCode 147 — Insertion Sort List(C++ Java Python)
- LeetCode 142 — Linked List Cycle II(C++ Java Python)
- [LeetCode] 005. Longest Palindromic Substring (Medium) (C++/Java/Python)
- LeetCode 149 — Max Points on a Line(C++ Java Python)
- LeetCode 70 — Climbing Stairs(C++ Java Python)
- [LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
- LeetCode 33 — Search in Rotated Sorted Array(C++ Java Python)
- LeetCode 4 — Median of Two Sorted Arrays (C++ Java Python)
- [LeetCode] 006. ZigZag Conversion (Easy) (C++/Java/Python)
- LeetCode 112 — Path Sum(C++ Java Python)