diff --git a/50/50.md b/50/50.md new file mode 100644 index 0000000..8432c2d --- /dev/null +++ b/50/50.md @@ -0,0 +1,79 @@ +## 何も見ずに解いてみる + +```cpp +class Solution { +public: + double myPow(double x, long long n) { + if (n == 0) { + return 1; + } + if (n < 0) { + return 1 / myPow(x, -n); + } + vector power_of_2_cache = {1}; + while (power_of_2_cache.size() < 32) { + long long new_power_of_2 = power_of_2_cache.back() * 2; + if (new_power_of_2 > n) { + break; + } + power_of_2_cache.push_back(new_power_of_2); + } + vector n_components_in_power_of_2; + for (int exp = power_of_2_cache.size() - 1; exp >= 0; --exp) { + if (power_of_2_cache[exp] <= n) { + n -= power_of_2_cache[exp]; + n_components_in_power_of_2.push_back(exp); + } + } + vector power_of_x_cache = {x}; + for (int exp = 1; exp <= n_components_in_power_of_2.front(); ++exp) { + power_of_x_cache.push_back(power_of_x_cache.back() * power_of_x_cache.back()); + } + double result = 1; + for (int component : n_components_in_power_of_2) { + result *= power_of_x_cache[component]; + } + return result; + } +}; +``` + +n == -2^31 の時に-nがintにcastできなくてエラーになった(intの表現範囲が-2^31 <= n <= 2^31 - 1のため)のでとりあえず関連する型を全部long longにして無理やり通しました + +## 他の人のコードを見てみる + +https://github.com/tokuhirat/LeetCode/pull/45/files +https://github.com/ryosuketc/leetcode_arai60/pull/34/files +https://github.com/Ryotaro25/leetcode_first60/pull/48 + +自分は非常に面倒なことをしていたらしい。。。 + +## 最終コード + +```cpp +class Solution { +public: + double myPow(double x, int n) { + if (n == 0) { + return 1.0; + } + if (n < 0) { + // cast to long long to handle INT_MIN; + return 1.0 / _myPow(x, -(long long)n); + } + return _myPow(x, n); + } +private: + double _myPow(double x, long long n) { + double result = 1.0; + while (n) { + if (n % 2 == 1) { + result *= x; + } + x *= x; + n /= 2; + } + return result; + } +}; +```