leet-code/src/main/java/leetcode/editor/cn/PowxN.java

36 lines
908 B
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//实现 pow(x, n) ,即计算 x 的 n 次幂函数x⁴
//
// Related Topics 递归 数学 👍 718 👎 0
package leetcode.editor.cn;
//50:Pow(x, n)
class PowxN {
public static void main(String[] args) {
//测试代码
Solution solution = new PowxN().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public double myPow(double x, int n) {
double ans = 1;
if (n < 0) {
x = 1 / x;
}
long exp = n;
exp = Math.abs(exp);
while (exp > 0) {
if (exp % 2 == 1) {
ans = ans * x;
}
x *= x;
exp /= 2;
}
return ans;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}