Leetcode–pow(x, n)

The Problem:

Implement pow(x, n).

Notes:

  1. This is a problem that can easily use recursion to solve. Be careful about negative n.

Java Solution

public class Solution {
    public double pow(double x, int n) {
        if(n==0) return 1;
        if(n==1)return x;
        if(n<0){
            x = 1/x;
            n = -n;
        }
        
        double half = pow(x, n/2);
        if(n%2==0)
            return half * half;
        else
            return half * half * x;
    }
}
Advertisements

One thought on “Leetcode–pow(x, n)

  1. Pingback: Leetcode–Sqrt(x) | Linchi is coding

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