[leetcode] Pow(x, n)

Implement pow(x, n).

https://oj.leetcode.com/problems/powx-n/

思路:不要连续乘n次,会超时。递归求解,注意不要写成重复计算,有正负数处理。

public class Solution {
	public double pow(double x, int n) {
		if (n == 0)
			return 1;

		double res = 1;
		long limit = n;
		limit = limit < 0 ? -limit : limit;
		res = recursivePow(x, limit);

		if (n < 0)
			res = 1.0 / res;

		return res;

	}

	private double recursivePow(double x, long n) {
		if (n == 1)
			return x;
		double half = recursivePow(x, n / 2);
		if (n % 2 == 0) {
			return half * half;
		} else {
			return half * half * x;

		}

	}

	public static void main(String[] args) {
		System.out.println(new Solution().pow(1.00000, -2147483648));
	}
}



你可能感兴趣的:(java,LeetCode,recursion)