Skip to content

Instantly share code, notes, and snippets.

@adamkorg
Created August 6, 2019 00:02
Show Gist options
  • Save adamkorg/2982fd48ba21a3b364b123de963cb902 to your computer and use it in GitHub Desktop.
Save adamkorg/2982fd48ba21a3b364b123de963cb902 to your computer and use it in GitHub Desktop.
Leetcode 50: Pow(x, n)
#include <iostream>
using namespace std;
double myPow(double x, int n) {
if (n==0)
return (x<0) ? -1 : 1;
long int e = n; //one of the test cases uses INT_MIN, which exceeds range when doing * -1, so long int increases range
if (e<0) {
x = 1/x;
e = e * -1;
}
double res = 1;
while (e > 0) {
if (e & 1)
res = res * x; //if exponent is odd then multiply res by our current factor of x
//due to above, n is now effectively even
e = e >> 1; //bitshift n, i.e. divide exponent by 2
x = x * x; //square x, i.e. x -> x^2
}
return res;
}
int main() {
cout << myPow(2.1, 3 ) << "\n"; //myPow2(0.00001, 2147483647) << "\n"; //myPow2(3,5) << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment