Ai
1 Star 0 Fork 0

amusement1234/LeetCode_Java

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
50.pow-x-n.java 1.72 KB
一键复制 编辑 原始数据 按行查看 历史
amusement1234 提交于 2021-11-14 16:17 +08:00 . update
/*
* @lc app=leetcode.cn id=50 lang=java
*
* [50] Pow(x, n)
*
* https://leetcode-cn.com/problems/powx-n/description/
*
* algorithms
* Medium (33.42%)
* Likes: 231
* Dislikes: 0
* Total Accepted: 43.1K
* Total Submissions: 128.7K
* Testcase Example: '2.00000\n10'
*
* 实现 pow(x, n) ,即计算 x 的 n 次幂函数。
*
* 示例 1:
*
* 输入: 2.00000, 10
* 输出: 1024.00000
*
*
* 示例 2:
*
* 输入: 2.10000, 3
* 输出: 9.26100
*
*
* 示例 3:
*
* 输入: 2.00000, -2
* 输出: 0.25000
* 解释: 2^-2 = 1/2^2 = 1/4 = 0.25
*
* 说明:
*
*
* -100.0 < x < 100.0
* n 是 32 位有符号整数,其数值范围是 [−2^31, 2^31 − 1] 。
*
*
*/
// @lc code=start
class Solution {
public double myPow(double x, int n) {
// 解法1:递归
if (n < 0) {
n = -n;
x = 1 / x;
}
return fastPow(x, n);
// 解法2:
if (n == 0)
return 1.0;
if (n == Integer.MIN_VALUE) {
x = x * x;
n = n / 2;
}
if (n < 0) {
n = -n;
x = 1 / x;
}
return (n % 2 == 0) ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2);
}
private double fastPow(double x, int n) {
//分治
//x^n ---> 2^10 -> 2^5 ->(2^2)*2
//1、terminator 终止条件
if (n == 0) {
return 1.0;
}
//2、process. split problem
//3. drill down, merge
double half = fastPow(x, n / 2);
//merge
if (n % 2 == 0) {
return half * half;
} else {
return half * half * x;
}
//4.reverse status
}
}
// @lc code=end
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/amusement1234/LeetCode_Java.git
git@gitee.com:amusement1234/LeetCode_Java.git
amusement1234
LeetCode_Java
LeetCode_Java
master

搜索帮助