From b482a38e65a8591bbbf17e732dbc59bc06cf36ab Mon Sep 17 00:00:00 2001
From: mike <59136831+Mike0121@users.noreply.github.com>
Date: Tue, 21 May 2024 19:06:46 +0900
Subject: [PATCH] Create 50. Pow(x, n).md
https://leetcode.com/problems/powx-n/description/
---
.../50. Pow(x, n).md" | 97 +++++++++++++++++++
1 file changed, 97 insertions(+)
create mode 100644 "\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/50. Pow(x, n).md"
diff --git "a/\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/50. Pow(x, n).md" "b/\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/50. Pow(x, n).md"
new file mode 100644
index 0000000..35840d6
--- /dev/null
+++ "b/\347\253\266\346\212\200\343\203\227\343\203\255\345\260\261\346\264\273\351\203\250PR\347\224\250/50. Pow(x, n).md"
@@ -0,0 +1,97 @@
+```
+負の数の割り算と余り、言語によって振る舞いが色々なので自分の使い慣れたものについては覚えておきましょう。
+```
+
+## 計算式による解法
+---
+時間計算量: O(1)
+空間計算量: O(1)
+```python
+class Solution:
+ def myPow(self, x: float, n: int) -> float:
+ return float(x ** n)
+```
+
+## 再帰による解法 (maximum recursion depth exceeded)
+---
+
+### 1回目
+時間計算量: O(N)
+空間計算量: O(N)
+よく考えたら、```if n == 1: return x```は不要。
+また、n == -1 は、最初にnが正負かで値の更新を行った方が、わかりやすい。
+(2回目以降で反映。)
+
+```python
+class Solution:
+ def myPow(self, x: float, n: int) -> float:
+ if n == 0:
+ return 1
+ if n == 1:
+ return x
+ if n == -1:
+ return 1 / x
+
+ return x * self.myPow(x, n - 1) if n > 0 else 1 / x * self.myPow(x, n + 1)
+```
+
+### 2回目
+時間計算量: O(logN)
+空間計算量: O(logN)
+
+分割統治法のイメージで書いたが、直感的に何をしているのかわかづらい。
+```python
+class Solution:
+ def myPow(self, x: float, n: int) -> float:
+ if n == 0:
+ return 1
+ if n < 0:
+ x = 1 / x
+ n *= -1
+
+ divided_prod = self.myPow(x, n // 2)
+ if n % 2 == 0:
+ return divided_prod * divided_prod
+ else:
+ return divided_prod * divided_prod * x
+```
+
+### 3回目
+時間計算量: O(logN)
+空間計算量: O(logN)
+```python
+class Solution:
+ def myPow(self, x: float, n: int) -> float:
+ if n == 0:
+ return 1
+ if n < 0:
+ x = 1 /x
+ n *= -1
+ if n % 2 == 0:
+ return self.myPow(x * x, n // 2)
+ else:
+ return x * self.myPow(x * x, n // 2)
+```
+
+
+
+## Interationによる解法
+---
+時間計算量: O(logN)
+空間計算量: O(logN)
+```python
+class Solution:
+ def myPow(self, x: float, n: int) -> float:
+ if n < 0:
+ x = 1 /x
+ n *= -1
+
+ accumulated_prod = 1
+ while n > 0:
+ if n % 2 != 0:
+ accumulated_prod *= x
+ x *= x
+ n //= 2
+
+ return accumulated_prod
+```