From 2687d4f02ef1b347b4a456ccde6b0793afb760cd Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Sat, 15 Mar 2025 00:07:26 +0800 Subject: [PATCH] feat: 50_pow_x_n --- 50_pow_x_n/main.cpp | 52 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 50_pow_x_n/main.cpp diff --git a/50_pow_x_n/main.cpp b/50_pow_x_n/main.cpp new file mode 100644 index 0000000..83ea728 --- /dev/null +++ b/50_pow_x_n/main.cpp @@ -0,0 +1,52 @@ +#include +using namespace std; + +class Solution { + public: + double myPow(double x, long long n) { + if (x == 0) return 0; + if (n == 0) return 1; + + bool isNeg = n < 0; + n = abs(n); + + int logn = (int)log2(n); + + vector expTable{x}; + + for (int i = 1; i < logn + 1; i++) { + expTable.emplace_back(expTable.back() * expTable.back()); + } + + double result = 1.0; + for (int i = 0; i < logn + 1; i++) { + if (n & 1) result *= expTable[i]; + n >>= 1; + } + + if (isNeg) result = 1.0 / result; + + return result; + } +}; + +/* + + 1010 +&0001 +----- + 0 + + 101 +& 001 +----- + 1 + +x^10 + +x^8 1 +x^4 0 +x^2 1 +x^1 0 + +*/