LeetCode 50 — Pow(x, n)(C++ Java Python)

题目:http://oj.leetcode.com/problems/powx-n/

Implement pow(x, n).

题目翻译:

        实现pow(x,n)。
分析:

        二分。

C++实现:

class Solution {
public:
    double pow(double x, int n) {
    	if(n < 0)
    	{
    	    return 1.0 / power(x, -n);
    	}
    	else
    	{
        	return power(x, n);
    	}
    }

    double power(double x, int n) {
    	if(n == 0)
    	{
    		return 1;
    	}

    	double tmp = pow(x, n / 2);

    	if(n & 0x01)
    	{
    	    return tmp * tmp * x;
    	}
    	else
    	{
    	    return tmp * tmp;
    	}
    }
};

Java实现:

public class Solution {
    public double pow(double x, int n) {
        if (n < 0) {
			return 1.0 / power(x, -n);
		} else {
			return power(x, n);
		}
	}

	public double power(double x, long n) {
		if (n == 0) {
			return 1;
		}

		double tmp = power(x, n / 2);

		if ((n & 0x01) == 1) {
			return tmp * tmp * x;
		} else {
			return tmp * tmp;
		}
	}
}

Python实现:

class Solution:
    # @param x, a float
    # @param n, a integer
    # @return a float
    def pow(self, x, n):
        if n < 0:
            return 1.0 / self.power(x, -n)
        else:
            return self.power(x, n)
    
    def power(self, x, n):
        if n == 0:
            return 1
        
        tmp = self.power(x, n / 2)
        
        if n & 0x01 == 1:
            return tmp * tmp * x
        else:
            return tmp * tmp

        感谢阅读,欢迎评论!

你可能感兴趣的:(LeetCode)