lc-50


//Implement pow(x, n), which calculates x raised to the power n (i.e., 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/22 = 1/4 = 0.25
// 
//
// 
// Constraints: 
//
// 
// -100.0 < x < 100.0 
// -231 <= n <= 231-1 
// -104 <= xn <= 104 
// 
// Related Topics Math Recursion 
// 👍 5102 👎 5875


//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public double myPow(double x, int n) {
        if (n == 0 || x == 1.0) {
            return 1.0;
        }

        if (n == Integer.MIN_VALUE) {
            if (x == -1.0) {
                return 1.0;
            } else {
                return 0.0;
            }
        }

        boolean isMinus = n < 0;

        if (isMinus) {
            n = -n;
        }

        double result = 1.0;

        while (n > 0) {
            int i = n & 0x01;

            if (i == 1) {
                result *= x;
            }

            x = x * x;
            n = n >> 1;
        }

        if (isMinus) {
            result = 1.0 / result;
        }

        return result;

    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !