LeetCode 题解(173): Pow(x, n)

来源:互联网 发布:数据结构与算法的关系 编辑:程序博客网 时间:2024/06/06 16:45

题目:

Implement pow(x, n).

题解:

要用二分法递归。还要区分n的正负。

C++版:

class Solution {public:    double myPow(double x, int n) {        if(n == 0) return 1;        if(n == 1) return x;        double temp = myPow(x, abs(n / 2));        if(n > 0) {            if(n & 1) return temp * temp * x;            else return temp * temp;        } else {            if(n & 1) return 1 / (temp * temp * x);            else return 1 / (temp * temp);        }    }};

Java版:

public class Solution {    public double myPow(double x, int n) {        if(n == 0) return 1;        if(n == 1) return x;        double temp = myPow(x, Math.abs(n / 2));        if(n > 0) {            if((n & 1) == 0) return temp * temp;            else return temp * temp * x;        } else {            if((n & 1) == 0) return 1 / (temp * temp);            else return 1 / (temp * temp * x);        }    }}

Python版:

class Solution:    # @param {float} x    # @param {integer} n    # @return {float}    def myPow(self, x, n):        if n == 0:            return 1.0        if n == 1:            return x        if n > 1:            return self.pow(x, n)        else:            return 1.0 / self.pow(x, -n)                def pow(self, x, n):        if n == 0:            return 1.0        if n == 1:            return x        temp = self.pow(x, n / 2)        if n % 2 == 0:            return temp * temp        else:            return temp * temp * x

0 0