Răsfoiți Sursa

#feat:leetcode p50题题解

yangyi 2 săptămâni în urmă
părinte
comite
5bb068e48c
1 a modificat fișierele cu 36 adăugiri și 0 ștergeri
  1. 36 0
      src/leetcode/p50/Solution.java

+ 36 - 0
src/leetcode/p50/Solution.java

@@ -0,0 +1,36 @@
+package leetcode.p50;
+
+/**
+ * @ProjectName: LeetCode
+ * @FileName: Solution
+ * @Author: 杨逸
+ * @Data:2025/8/12 18:08
+ * @Description: https://leetcode.cn/problems/powx-n/
+ *50. Pow(x, n)
+ */
+class Solution {
+    /**
+     * <img alt="lc50-3-c.png" title="'灵茶山艾府'提供的题解" src="https://pic.leetcode.cn/1728623430-RNGDEK-lc50-3-c.png">
+     * @param x 基数
+     * @param n 指数
+     * @return
+     */
+    public double myPow(double x, int n) {
+        long N = n;
+        if (N < 0){
+            //负指数的情况
+            N = -N;
+            x = 1 / x;
+        }
+        double res = 1;
+        double cur = x;
+        while(N != 0){
+            if ((N & 1) == 1){
+                res *= cur;
+            }
+            cur *= cur;
+            N >>= 1;
+        }
+        return res;
+    }
+}