• LeetCode //C - 50. Pow(x, n)


    50. Pow(x, n)

    Implement pow(x, n), which calculates x raised to the power n (i.e., x n x^n xn).
     

    Example 1:

    Input: x = 2.00000, n = 10
    Output: 1024.00000

    Example 2:

    Input: x = 2.10000, n = 3
    Output: 9.26100

    Example 3:

    Input: x = 2.00000, n = -2
    Output: 0.25000
    Explanation: 2 − 2 = 1 / 2 2 = 1 / 4 = 0.25 2^{-2} = 1/2^2 = 1/4 = 0.25 22=1/22=1/4=0.25

    Constraints:
    • -100.0 < x < 100.0
    • − 2 31 < = n < = 2 31 − 1 -2^{31} <= n <= 2^{31}-1 231<=n<=2311
    • n is an integer.
    • Either x is not zero or n > 0.
    • − 1 0 4 < = x n < = 1 0 4 -10^4 <= x^n <= 10^4 104<=xn<=104

    From: LeetCode
    Link: 50. Pow(x, n)


    Solution:

    Ideas:
    1. The powHelper function recursively calculates the power for a non-negative exponent.
    2. For the case when n is negative, it calculates the power for the positive value of n and then returns the reciprocal of the result.
    3. The isNegative flag is used to check if the original n was negative.
    4. Special care is taken to avoid overflow when converting a negative n to its positive counterpart, especially important when n is INT_MIN.
    Code:
    double myPow(double x, int n) {
        // Helper function to calculate power for non-negative exponent
        double powHelper(double x, unsigned int n) {
            if (n == 0) return 1;
            double half = powHelper(x, n / 2);
            if (n % 2 == 0) 
                return half * half;
            else 
                return half * half * x;
        }
    
        // Handling the case when n is negative
        bool isNegative = false;
        unsigned int positiveN = n;
        if (n < 0) {
            isNegative = true;
            positiveN = -((unsigned int)n); // Convert to positive, handle overflow
        }
    
        double result = powHelper(x, positiveN);
    
        // If n is negative, return the reciprocal
        return isNegative ? 1 / result : result;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
  • 相关阅读:
    Python编译后的pyc文件转py源码文件
    Vue3 之 Vue - Router
    CSS - PC / 移动端左右满屏高度布局(100% 高度 + 溢出滚动条)
    CSS 基础
    建模配置 | Revit建模到底需要什么配置
    matlab查找符号表达式中的符号变量
    腾讯云EKS 上部署 eshopondapr
    生产脚本1
    Golang sync.WaitGroup
    校验验证码是否过期(定时刷新验证码)
  • 原文地址:https://blog.csdn.net/navicheung/article/details/134522827