美文网首页
LeetCode代码分析——50. Pow(x, n)(细节,i

LeetCode代码分析——50. Pow(x, n)(细节,i

作者: JackpotDC | 来源:发表于2018-06-19 16:08 被阅读13次

    题目描述

    Implement pow(x, n), which calculates x raised to the power n (xn).
    实现x的n次方操作。

    Example 1:

    Input: 2.00000, 10
    Output: 1024.00000

    Example 2:

    Input: 2.10000, 3
    Output: 9.26100

    Example 3:

    Input: 2.00000, -2
    Output: 0.25000
    Explanation: 2-2 = 1/22 = 1/4 = 0.25

    Note:

    • -100.0 < x < 100.0
    • n is a 32-bit signed integer, within the range [−231, 231 − 1]

    思路分析

    这个题很简单,最简单的方法是遍历,result*=x;

    • 但是这样的话复杂度是O(n)。还可以灵活利用已有的结果来降低复杂度,通过递归,以210为例,可以将210递归为25 * 25,依次向下求解。
    • 另一方面注意到n的范围是全部int的范围,而int的范围是不对称的([−231, 231 − 1]),因此需要注意负数处理时不能直接将n取-n(通过x-(n+1)*x递归,或者对Integer.MIN_VALUE进行特殊判断)。
    • 另外注意在对奇偶进行判断和除2时尽量使用位运算>> << & |),可以更好的利用计算机二进制的特性提升性能。(《剑指offer》

    代码实现

    public class Solution {
    
        /**
         * 304 / 304 test cases passed.
         *  Status: Accepted
         *  Runtime: 22 ms
         * @param x
         * @param n
         * @return
         */
        public double myPow(double x, int n) {
            if (n < 0) {
                return 1 / x * myPow(1 / x, -(n + 1));
            }
            if (n == 0) {
                return 1;
            }
            if (n == 1) {
                return x;
            }
    
            double half = myPow(x, n >> 1);
            half *= half;
    
            if ((n & 1) == 1) {
                half *= x;
            }
    
            return half;
        }
    
    }
    

    相关文章

      网友评论

          本文标题:LeetCode代码分析——50. Pow(x, n)(细节,i

          本文链接:https://www.haomeiwen.com/subject/jjnaeftx.html