Created
August 6, 2019 00:02
-
-
Save adamkorg/2982fd48ba21a3b364b123de963cb902 to your computer and use it in GitHub Desktop.
Leetcode 50: Pow(x, n)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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