Pow(x, n)

Implement pow(x, n).

C++:
01 class Solution {
02 public:
03     double pow(double x, int n) {
04         // Start typing your C/C++ solution below
05         // DO NOT write int main() function
06         if(n==0)
07             return 1;
08         if(n==1)
09             return x;
10         int sign=n>=0?1:-1;
11         n=n>-n?n:n;
12         if(n%2==0)
13         {
14             double t=pow(x,n/2);
15             return sign==1?t*t:1/(t*t);
16         }
17         else
18         {
19             double t=pow(x,n/2);
20             return sign==1?t*t*x:1/(t*t*x);
21         }
22     }
23 };
Advertisements
This entry was posted in Number trick, Recursive. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s