Skip to content

Instantly share code, notes, and snippets.

@sonsongithub
Created March 26, 2019 08:59
Show Gist options
  • Select an option

  • Save sonsongithub/d331a56a2e6e9359fa06a0e47fa77fdd to your computer and use it in GitHub Desktop.

Select an option

Save sonsongithub/d331a56a2e6e9359fa06a0e47fa77fdd to your computer and use it in GitHub Desktop.
class Solution {
public:
unordered_map<int, double> mp;
double myPow(double x, int n) {
int64_t m = (int64_t)n;
if (n < 0) {
x = 1 / x;
m = -m;
}
mp[0] = 1;
mp[1] = x;
return recursivePow(x, m);
}
double recursivePow(double x, int64_t n) {
auto itr = mp.find(n);
if(itr != mp.end()) {
return itr->second;
}
auto left = n / 2;
auto right = n - left;
auto left_result = recursivePow(x, left);
auto right_result = recursivePow(x, right);
auto temp = left_result * right_result;
mp[n] = temp;
return temp;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment