Implement pow(x, n), which calculates x raised to the power n (xn).
Example 1:
Input: 2.00000, 10 Output: 1024.00000 Example 2:
Input: 2.10000, 3 Output: 9.26100 Example 3:
Input: 2.00000, -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25 Note:
-100.0 < x < 100.0 n is a 32-bit signed integer, within the range [−231, 231 − 1]
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/powx-n 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

所以求 x的n次方 可以转换为 e的 n*ln(x)次方的解法
当然我是想不出来了,看的评论区.
exp(n*log(abs(x)));c++里面有 exp 函数 可以求 e的 n次方.
class Solution {
public:
double myPow(double x, int n) {
if(x == 0) return 0;
double ans;
if(x > 0 || ((x < 0) && (n % 2 == 0))) ans = exp(n*log(abs(x)));
else ans = -exp(n*log(-x));
return ans;
}
};
作者:w-avan
链接:https://leetcode-cn.com/problems/powx-n/solution/c-ji-bai-shuang-bai-qiao-yong-dui-shu-han-shu-by-w/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。这是 我能想到的 不是暴力的 一种解法了
class Solution {
public double myPow(double x, int n) {
double ans = 1;
int sign = 1;
if (n < 0) {
sign = -1;
if (n == Integer.MIN_VALUE) {
n = -(n + 1);
ans *= x;
} else {
n = -n;
}
}
while (n > 0) {
if (n % 2 == 1)
ans *= x;
n /= 2;
x *= x;
}
return sign == 1 ? ans : 1 / ans;
}
}
作者:iame
链接:https://leetcode-cn.com/problems/powx-n/solution/50-powx-n-java-xun-huan-qiu-jie-by-iame/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。if (n < 0) { // n是 负值特殊考虑 sign = -1; if (n == Integer.MIN_VALUE) { // 最小值特殊考虑 n = -(n + 1);// 如果是 最小值了 取负值会溢出 所以可以先拿出来一个 ans *= x 然后就可以理所应当的 -n -1; ans *= x;
/*
*/ } else { n = -n; // 负值转换成正值 最后返回倒数即可 } }
// 从这里开始正式运算 while (n > 0) { if (n % 2 == 1) ans *= x; // 不是2的倍数就乘 多出来的一次 n /= 2; // 平方 n除二 x *= x; }
return sign == 1 ? ans : 1 / ans; // 负数返回倒数。
if(n == Integer.MIN_VALUE){
n = -(n + 2);
ans *= x;
ans *= x;
//return 0;
同理这样改也是对的,虽然有点画蛇添足 但是可以理解 为何
