Pow(x, n) LeetCode solution in C++
1class Solution {2public:3double myPow(double x, int n) {4if (n == 0) return 1; // anything to the power 0 is 156if (x == 1 || n == 1) return x; // 1 to the power anything = 1 or x to the power 1 = x78double ans = 1;910long long int a = abs(n); // since int range is from -2147483648 to 2147483647, so it11// can't store absolute value of -21474836481213if (n < 0) { // as 2^(-2) = 1/2^214if (a % 2 == 0)15ans = 1 / myPow(x * x, a / 2);16else17ans = 1 / (x * myPow(x, a - 1));18} else {19if (a % 2 == 0)20ans = myPow(x * x, a / 2);21else22ans = x * myPow(x, a - 1);23}2425return ans;26}27};